gpt4 book ai didi

java - 两个线程进入 runnable 的同步方法

转载 作者:行者123 更新时间:2023-11-29 07:13:47 26 4
gpt4 key购买 nike

这是我遇到问题的代码 --

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 while T1 is waiting inside? and Why T2 prints i=5 in aMethod.

最佳答案

当你执行wait时,你的线程释放锁并进入等待状态。这时允许其他线程进入该方法。您正在使用 Runnable 的单个实例,因此当一个线程将其设置为 5 时,另一个线程将读取该值。

关于java - 两个线程进入 runnable 的同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11491533/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com