这是我遇到问题的代码 --
public class WaitTest {
public static void main(String[] args) {
Runner rr = new Runner();
Thread t1 = new Thread(rr,"T1");
Thread t2 = new Thread(rr,"T2");
t1.start();
t2.start();
}
}
class Runner implements Runnable{
int i=0;
public void run(){
try{
if(Thread.currentThread().getName().equals("T1")){
bMethod();
aMethod();
}
else{
aMethod();
bMethod();
}
}catch(Exception e){}
}
public synchronized void aMethod() throws Exception{
System.out.println("i="+i+",Now going to Wait in aMethod "+Thread.currentThread().getName());
Thread.currentThread().wait();
System.out.println("Exiting aMethod "+Thread.currentThread().getName());
}
public synchronized void bMethod() throws Exception{
System.out.println("i="+i+",Now going to Wait bMethod "+Thread.currentThread().getName());
i=5;
notifyAll();
System.out.println("Exiting bMethod "+Thread.currentThread().getName());
}
}
输出是:
i=0,Now going to Wait bMethod T1
Exiting bMethod T1
i=5,Now going to Wait in aMethod T1
i=5,Now going to Wait in aMethod T2
我的问题是:
Why T2 enters in
aMethod
whileT1
is waiting inside? and WhyT2
printsi=5
inaMethod.
最佳答案
当你执行wait
时,你的线程释放锁并进入等待状态。这时允许其他线程进入该方法。您正在使用 Runnable
的单个实例,因此当一个线程将其设置为 5 时,另一个线程将读取该值。
关于java - 两个线程进入 runnable 的同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11491533/