通知线程未退出等待状态 [英] Notify not getting the thread out of wait state
问题描述
我正在尝试使用2个线程.一个线程只打印奇数,另一个线程只打印偶数,这必须是另一种操作.
I am trying to use 2 threads. 1 thread prints only odd number and the other thread prints only even number and It has to be an alternative operation.
例如:
Thread1 1
Thread2 2
Thread1 3
Thread2 4
and so on..
下面是该程序,请让我知道我要去哪里了,因为即使线程2正在通知它,线程1也不会退出等待状态.
Below is the program, please let me know where I am going wrong as the thread1 is not coming out of wait state even when the thread2 is notifying it..
public class ThreadInteraction {
public static void main(String[] args) {
new ThreadInteraction().test();
}
private void test() {
ThreadA ta = new ThreadA();
Thread t = new Thread(ta);
t.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
for(int i=2;i<=50;){
System.out.println("Thread2 "+i);
synchronized (t) {
try {
t.notify();
t.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
i=i+2;
}
}
}
class ThreadA implements Runnable{
@Override
public void run() {
for(int i=1;i<50;){
System.out.println("Thread1 "+i);
synchronized (this) {
try {
notify();
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i=i+2;
}
}
}
推荐答案
问题是在一种情况下您锁定了Thread t
[synchronized(t)],而在另一种情况下则锁定了TheadA
对象本身[已同步(this)].
Problem is that in one case you are taking lock on Thread t
[synchronized (t) ] while in other case you are taking lock on TheadA
object itself [synchronized(this)].
如果您希望线程彼此交谈,则两个线程都应仅锁定同一对象,然后等待通知将按预期工作.
If you want threads to talk to each other then both should take lock on same object only then wait notify will work as you expect.
程序中还有另一个问题,您没有使用任何变量在2个线程之间进行协调.所以您可能会看到像这样的2,1,4,3 ...等输出.关键是线程将交替工作,但不能按顺序工作. 因此,您应该在2个线程之间共享一个变量,该变量应该增加. 第二个问题是您不关心虚假的唤醒调用[请阅读有关此文档的一些文档],您应该始终在while循环内调用wait.
There is another problem in your program, you are not using any variable to coordinate between 2 threads. SO you may see output like this 2,1,4,3...so on. Point is threads will work alternately but not in sequence. So you should share a single variable between 2 threads which should be incremented. Second issue is you are not taking care of spurious wake up calls [read some docs on this], you should always have wait called inside a while loop.
这篇关于通知线程未退出等待状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!