java – 为什么下面的程序,没有睡眠会进入死锁状态,但是在睡眠状
发布时间:2020-12-15 04:28:40 所属栏目:Java 来源:网络整理
导读:public class ThreadTest {public static void main(String[] args) throws InterruptedException { ExampleTest obj = new ExampleTest(); Thread t1 = new Thread(new Runn(obj)); Thread t2 = new Thread(new Runn(obj)); Thread t3 = new Thread(new Run
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
ExampleTest obj = new ExampleTest();
Thread t1 = new Thread(new Runn(obj));
Thread t2 = new Thread(new Runn(obj));
Thread t3 = new Thread(new Runn(obj));
t1.start();
t2.start();
t3.start();
//Thread.sleep(1);
obj.exit();
}
} class ExampleTest {
public synchronized void enter() {
try {
System.out.println("printed " +Thread.currentThread().getName() +" inside wait");
this.wait();
System.out.println("printed " +Thread.currentThread().getName() +" exit wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("printed " +Thread.currentThread().getName() +" at time: "+System.currentTimeMillis());
}
public synchronized void exit() {
this.notifyAll();
}
} class Runn implements Runnable {
ExampleTest obj;
public Runn(ExampleTest obj) {
this.obj = obj;
}
@Override
public void run() {
obj.enter();
}
}
解决方法
没有sleep语句的语句obj.exit();很可能在所有线程都达到等待状态之前执行.即.在至少有一个线程处于等待状态之前,notifyAll调用将结束.因此,至少有一个线程将处于等待状态,等待其他线程通知它并唤醒.但是,因为obj.exit()已经完成,所以永远不会发生这种情况.
在你的睡眠声明到位后,你的所有线程都有机会达到他们的等待状态,睡眠后你的notifyAll调用会将它们全部唤醒.唤醒的顺序不是确定性的,并且将由线程调度程序处理. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
