【发布时间】:2016-12-08 02:49:48
【问题描述】:
直到现在我都知道等待总是需要通知才能正常工作。但是当尝试下面的代码时,我对等待和通知的工作有点困惑。我创建了三个线程 t1、t2、t3 并分别传递了可运行的 T1、T2 和 T3。据我说,当我启动三个线程时,只有 t1 应该打印,t2 和 t3 应该进入等待状态并继续等待,因为没有人是通知。
但是 o/p 对我来说是不可预测的。有人可以解释一下吗。下面是我的课程。
package com.vikash.Threading;
class T1 implements Runnable {
private State state;
public T1(State state) {
this.state=state;
}
@Override
public void run() {
synchronized (state) {
while(state.getState()!=1) {
try {
state.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (state) {
System.out.println(Thread.currentThread().getName());
state.setState(2);
}
}
}
}
class T2 implements Runnable {
private State state;
public T2(State state) {
this.state=state;
}
@Override
public void run() {
synchronized (state) {
while(state.getState()!=2) {
try {
state.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (state) {
System.out.println(Thread.currentThread().getName());
state.setState(3);
}
}
}
}
class T3 implements Runnable {
private State state;
public T3(State state) {
this.state=state;
}
@Override
public void run() {
synchronized (state) {
while(state.getState()!=3) {
try {
state.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (state) {
System.out.println(Thread.currentThread().getName());
state.setState(1);
}
}
}
}
public class Sequence {
public static void main(String[] args) {
State state=new State();
Thread t1=new Thread(new T1(state),"First");
Thread t2=new Thread(new T2(state),"Second");
Thread t3=new Thread(new T3(state),"Third");
t1.start();
t2.start();
t3.start();
}
}
package com.vikash.Threading;
public class State {
private int state=1;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
根据评论,我正在修改我的问题。o/p 有时我得到第一秒但它不会终止,有时是第一秒第三和终止。
【问题讨论】:
-
请解释一下但是o/p对我来说是不可预测的
-
可能不是原因,但是你有没有意识到你已经嵌套了
synchronized见stackoverflow.com/a/10365261/2310289
标签: java multithreading wait notify