在java中跨类同步

时间:2016-04-06 23:00:42

标签: java multithreading class synchronized

我有两个并发运行的线程,一个主线程和一个旧的布尔变量类,我目前有一个thrad打印赔率和其他打印平均值,但我让他们等待彼此以便它按顺序打印1 - 100。

我目前在我的NumberPrinter类中引用一个布尔对象,我正在使用它来使一个线程进入等待状态以等待另一个。我知道如何在同一个类中进行同步,但是当我尝试跨线程进行同步时,它只是挂起并且看起来布尔变量没有被更新或与两个线程同步。至少这就是我认为是问题的原因

感谢任何建议表示赞赏

我的考试班

public class Test {

    public static void main(String[] args) throws InterruptedException {

        NumberPrinter np = new NumberPrinter();
        single ent = new single(np);// new state
        Double ont = new Double(np);// new state


        ent.start();
        ont.start();


    }

}

甚至

的课程
public class single extends Thread {

    private NumberPrinter printer;

    public single(NumberPrinter np) {
        this.printer = np;
    }

    public synchronized void run() {
        try {

            for (int i = 1; i <= 100; i++) {
                System.out.println(printer.isOdd);
                if (i % 2 == 0) {
                    if (printer.isOdd == true) {
                        wait();
                    }
                    System.out.println(i);
                    printer.isOdd = true;
                    notifyAll();
                }
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

奇数类

public class Double extends Thread {

    private NumberPrinter printer;
    public Double(NumberPrinter np) {
        this.printer = np;
    }


    public synchronized void run() {
        try {
            for (int i = 1; i <= 100; i++) {
                System.out.println(printer.isOdd);
                if (i % 2 == 1) {
                    if (printer.isOdd == false) {
                        wait();
                    }
                    System.out.println(getName() + ": " + i);
                    printer.isOdd = false;
                    notifyAll();
                }
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

保存布尔变量的类

package single;

public class NumberPrinter {

    public boolean isOdd = true;

}

1 个答案:

答案 0 :(得分:0)

需要从两个线程对同一个对象调用

waitnotifyAll。您还需要同步该对象。您正在使用线程实例,但有两个不同的实例。您可以使用printer对象,也可以创建new Object()并使用它。 wait也应该在while循环中使用,而不是if语句。

public void run() {
    try {
        for (int i = 1; i <= 100; i++) {
            synchronized(printer) {
                System.out.println(printer.isOdd);
                if (i % 2 == 1) {
                    while (printer.isOdd == false) {
                        printer.wait();
                    }
                    System.out.println(getName() + ": " + i);
                    printer.isOdd = false;
                    printer.notifyAll();
                }
            }
        }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}