Java多线程:启动2个线程,轮流打印1-100。结果是这样的:但它没有运行
两个线程需要按此顺序打印-
Thread1:0
Thread2:::0
Thread1:1
Thread2:::1
Thread1:2
Thread2:::2
Thread1:3
Thread2:::3
Thread1:::4
Thread2:::4
.
.
.
Thread1:100
Thread2:::100
...
目前这是我的代码,不知何故它卡住了。. 不知道为什么它没有按预期运行
public class Solution{
private volatile boolean isOneTurn;
public Solution(){
isOneTurn = true;
}
public void test(){
Thread t1 = new Thread(new MyThread1("Thread1"));
Thread t2 = new Thread(new MyThread2("Thread2"));
t1.start();
t2.start();
}
class MyThread1 implements Runnable {
public String name;
public MyThread1(String name) {
this.name = name;
}
@SneakyThrows
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
synchronized (this) {
if (!isOneTurn){
this.wait();
}
System.out.println(name + "-" + i);
isOneTurn = false;
this.notifyAll();
}
}
}
}
class MyThread2 implements Runnable {
public String name;
public MyThread2(String name) {
this.name = name;
}
@SneakyThrows
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
synchronized (this) {
if (isOneTurn){
this.wait();
}
System.out.println(name + "-" + i);
isOneTurn = true;
this.notifyAll();
}
}
}
}
}
我知道那里有很多类似的问题。但我只是想知道为什么我的代码没有按预期工作。
回答
如果您使用wait 和notify,则等待的线程需要能够期望另一个线程在调用wait 的同一对象实例上调用notify。您没有这样做,一个线程在 Thread1 的实例上同步,另一个实例在 Thread2 的实例上同步。结果是线程进入等待并且没有任何东西唤醒它们。
为了使锁定起作用,必须共享锁定。wait和notify方法使用被synchronized的隐式锁作为协调点,当一个线程调用synchronized对象上的notify时,只有调用该对象上的wait的线程才能被唤醒。
THE END
二维码