我想了解如何使两个线程在正确的时间互相挂起,我尝试研究文档和内容,但了解得还不够;我想制作一个程序,例如:
[ThreadA一次在ThreadB中写入一个int
作为属性,然后B打印它。A等待写入另一个int
,直到得到B的确认,确认前一个已打印,并且B必须等待A写入int
后再打印。
如果我要使用A/B.suspend()
和A/B.resume()
,情况会更加清楚,但是我不知道如何使用wait
和notify
做相同的事情。
这是我所做的一个示例(不起作用):
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();
}
}
ThreadA:
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甚至没有等待..
您可能考虑使用共享标志来决定每个线程何时可以访问变量。参见以下示例:processor.java每个方法(产生和使用)都在其自己的线程中独立执行(请参见app.java)。
他们使用列表的大小来决定是否可以访问列表。
希望有帮助