直到现在我才知道等待总是需要通知才能正常工作。但是当尝试下面的代码时,我对等待和通知的工作感到困惑。我创建了三个线程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;
}
}
根据评论,我正在修改我的问题。有时我得到第一名,并且它不会终止,有时候是第一名和第三名并且终止。
答案 0 :(得分:2)
您的期望是不正确的,您的所有主题都可以打印并在您的程序当前写入时结束(但这取决于随机机会)
这取决于哪个线程首先使用state
阻止synchronized
阻止synchronized (state)
的监视器。
考虑这个流程:
synchronized (state)
块。 T2和T3正在等待输入state.getState() == 1
块。state.state
,所以改为synchronized (state)
state.getState() == 2
块,假设它是T2(首先输入的是Java中未定义的行为,可能这是随机的)state.state
Intent