[英]Java Threads wait, notify in one class giving unexpected results
/ 我已经将以下程序编写为wait()和notify()。 但是在转到First put()方法之后,线程不再前进。 谁能解释一下我在以下代码中所犯的错误。 /
public class ThreadJoin {
public void buildThread() throws InterruptedException {
Adder a = new Adder("Test");
Thread t1 = new Thread(a, "First");
Thread t2 = new Thread(a, "second");
t1.start();
t2.start();
}
public static void main(String[] args) throws InterruptedException {
new ThreadJoin().buildThread();
}
}
class Adder implements Runnable {
String name;
int i;
private boolean suspendFlag = false;
public Adder(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
for(int i = 0; i < 10; i++){
put(i);
}
for(int j = 0 ; j < 10; j++){
get();
}
}
public synchronized void put(int i) {
this.i = i;
try {
while (suspendFlag) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("put: " + i+" currentThread: "+Thread.currentThread().getName());
suspendFlag = true;
notify();
}
public synchronized void get() {
System.out.println("Entering into the get method");
try {
if (!suspendFlag) {
wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("get: " + i+" currentThread: "+Thread.currentThread().getName());
suspendFlag = true;
notify();
}
}
哪个线程First
执行(例如First
)将执行synchronized
put
方法,从而锁定Adder
对象的监视器。 在这种情况下,另一个线程( second
)无法开始执行put
方法,因为它无法锁定同一Adder
对象的监视器。
因此, First
看到suspendFlag
为false
,因此跳过了while
。 它使supsedFlag
true
并调用notify()
。 当前没有线程正在Adder
对象上等待,因此对notify()
的调用没有任何作用。
当此线程结束put
方法的执行时,监视器将被释放, second
可能获取它。 如果发生这种情况,它将看到suspendFlag
为true
并进入while
块,执行wait()
。 这样做会释放监视器。 suspendFlag
仍然为true
。
执行返回到First
, First
循环进行for
然后重新调用put
。 它看到suspendFlag
为true
并进入while
循环,并调用wait()
。
现在,您的两个线程都处于wait
,没有任何notify
。 您的程序停顿了。
发生的情况的简单视图是,您有一个等待通知结构,该结构强制进行交替的put
和get
调用。 您有两个线程,每个线程put
在其第一个get
之前执行10次put
调用,因此无法进行交替。 这两个线程最终都put
等待另一个进行get
。
你可以改变你的设计允许多put
电话没有get
或更改驱动代码,这样一个线程并put
通话,另一种则get
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.