首先线程public class TestThread11 {
private static Object lock = new Object();
public void execute(){ // synchronized修饰
synchronized(lock){
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
if(i == 5){
try {
lock.wait();
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}
}
}再来class ThreadAA implements Runnable {
public void run() {
TestThread11 test = new TestThread11();
test.execute();
}
public static void main(String[] args)
{
Runnable runabble=new ThreadAA();
Thread a=new Thread(runabble,"A");
a.start();
Thread b=new Thread(runabble,"B");
b.start();
Thread c=new Thread(runabble,"C");
c.start();
}
} 2个线程的时候 还好说一个线程肯定会调用notify,另外一个线程的肯定会被唤醒。
但是如果3个以上的线程时,就有可能线程A 调用wait后,线程B调用notify,然后wait释放锁后,线程A继续运行完,然后会notify线程B继续运行完,在这过程,线程C可能一直都不会运行,但是线程A,B都运行完了,线程Cwait后 就没有线程来唤醒它了,导致死锁。这问题怎么解决?
private static Object lock = new Object();
public void execute(){ // synchronized修饰
synchronized(lock){
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
if(i == 5){
try {
lock.wait();
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}
}
}再来class ThreadAA implements Runnable {
public void run() {
TestThread11 test = new TestThread11();
test.execute();
}
public static void main(String[] args)
{
Runnable runabble=new ThreadAA();
Thread a=new Thread(runabble,"A");
a.start();
Thread b=new Thread(runabble,"B");
b.start();
Thread c=new Thread(runabble,"C");
c.start();
}
} 2个线程的时候 还好说一个线程肯定会调用notify,另外一个线程的肯定会被唤醒。
但是如果3个以上的线程时,就有可能线程A 调用wait后,线程B调用notify,然后wait释放锁后,线程A继续运行完,然后会notify线程B继续运行完,在这过程,线程C可能一直都不会运行,但是线程A,B都运行完了,线程Cwait后 就没有线程来唤醒它了,导致死锁。这问题怎么解决?
不过可以帮你降低出现死锁的概率,将lock.notify();更改为lock.notifyAll();