有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java程序在调用线程#join()方法时冻结

我需要创建一个程序,以两种方式实现比较和递增两个计数器:未同步和已同步。所以我基本上有两个字段int counter&;int counter2和run()方法,该方法只需迭代n次,比较计数器,递增计数器1,等待100毫秒,然后递增计数器2。 我有一个工作实现,但我需要使主线程最后完成,我有点困惑这样做。代码是:

public class Part3 {

    private int counter;    
    private int counter2;

    public synchronized boolean syncEquals() {
        return counter == counter2;
    }

    public synchronized void syncIncrement() {
        counter++;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        counter2++;
    }


    public static void main(final String[] args) throws InterruptedException {
        Part3 p = new Part3();
        p.compare();
        System.out.println("-----------------------");
        p.compareSync();
    }


    public void compare() throws InterruptedException {
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0; i < 10; i++) {
                    System.out.println((counter == counter2));
                    counter++;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    counter2++;
                }
            }
        });

        Thread t2 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0; i < 10; i++) {
                    System.out.println(counter == counter2);
                    counter++;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    counter2++;
                }
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();    
    }

    public synchronized void compareSync() throws InterruptedException {
        counter = 0;
        counter2 = 0;
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0; i < 10; i++) {
                    System.out.println(syncEquals());
                    syncIncrement();
                }
            }
        });

        Thread t2 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0; i < 10; i++) {
                    System.out.println(syncEquals());
                    syncIncrement();
                }
            }
        });

        t1.start();
        t2.start();
    }
}

问题是,当我在compareSync()中调用t1.join()t2.join()时,程序会冻结,甚至不会打印此方法的任何结果。我是线程新手,想知道我做错了什么,所以提前谢谢你


共 (0) 个答案