死锁
当业务比较复杂时,多线程应用里有可能会发生死锁
演示死锁
- 线程一占有对象一,试图占有对象二
- 线程二占有对象二,试图占有对象一
- 线程一等待线程二释放线程二
- 线程二等待线程一释放线程一
练习
package multiThread2;
public class main1 {
public static void main(String[] args) {
Animal a1 = new Animal();
Animal a2 = new Animal();
Animal a3 = new Animal();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (a1){
System.out.println("a1在做饭");
try {
Thread.sleep(1000);
}catch (Exception e){
throw new RuntimeException(e);
}
System.out.println("a1试图干饭");
System.out.println("a1等待着");
synchronized (a2){
System.out.println("a1 doing");
}
}
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (a2){
System.out.println("a2在做饭");
try {
Thread.sleep(1000);
}catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("a2试图干饭");
System.out.println("a2等待着");
synchronized (a3){
System.out.println("a2 doing");
}
}
}
});
t2.start();
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (a3){
System.out.println("a3在做饭");
}
try {
Thread.sleep(1000);
}catch (Exception e){
throw new RuntimeException(e);
}
System.out.println("a3试图干饭");
System.out.println("a3等待着");
synchronized (a1){
System.out.println("a3 doing");
}
}
});
t3.start();
}
}