如何使用等待/通知使这些线程交替工作?

时间:2020-05-10 09:47:38

标签: java multithreading wait notify

我想了解如何使两个线程在正确的时间互相挂起,我尝试研究文档和相关内容,但了解得还不够。我想制作一个像这样的程序:

线程A一次在线程B中写入一个$ brew update && brew upgrade python 作为属性,然后B将其打印出来。 A等待写入另一个int,直到从B确认已经打印了上一个int为止,并且B必须等待A写int才可以打印。

如果我使用A/B.suspend()A/B.resume(),情况会更加清楚,但是我不知道如何使用waitnotify做同样的事情

这是我所做的一个示例(不起作用):

public class Main {
    public static void main(String[] args) {
        Object lock=new Object();
        ThreadB tB=new ThreadB(lock);
        tB.start();
        ThreadA tA=new ThreadA(lock);
        tA.start();
    }
}

线程A:

public class ThreadA extends Thread {
    private Object lock;
    private ThreadB threadB;
    public ThreadA(Object b,ThreadB tb) {
        lock=b;
        threadB=tb;
    }
    public void run() {
        for(int i=0;i<10;i++) {
                threadB.setI(i);
                synchronized(lock) { //(try/catch omitted for shortness)
                    lock.notify();  //to tell B the int was loaded
                    lock.wait();    //to stop until B tells me that the int has been used
                }   
        }
        //join or something for B
    }   
}

线程B:


public class ThreadB extends Thread {
    private Object lock;
    int i;
    public ThreadB(Object b) {
        lock=b;
    }
    public void setI(int x) {
        i=x;
    }
    public void run() {
        while(true) {
            synchronized(lock) { //(try/catch omitted for shortness)
                lock.wait();    //to wait until A loaded the int
            }
            int a=i;
            System.out.println(a);
            synchronized(lock) {
                lock.notify();  //to tell A it can load the next int    
            }
        }
    }   
}

我当时想使用lock作为令牌,但我认为这还不够,例如,可能会发生A调用B的notify,然后B继续通知A,但是A没有还没等。

1 个答案:

答案 0 :(得分:0)

您可以考虑使用共享标志来确定每个线程何时可以访问变量。 请参见以下示例:processor.java 每个方法(产生和使用)都在其自己的线程中独立执行(请参见app.java)。

他们使用列表的大小来决定是否可以访问列表。

希望有帮助