我的线程为什么死锁了
有两个例子,第二个例子只是在第一个基础上 加了睡眠就一定死锁,这点还没有理解清楚
不会死锁
package com.deadlock.test1;
//程序可能执行很正常
//因为当第一个把o1,o2都锁住以后再释放,等释放完第二个再进行锁,那么程序就不会出问题
public class DeadLock {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
MyThread1 myThread1 = new MyThread1(o1,o2);
MyThreaad2 myThread2 = new MyThreaad2(o1,o2);
myThread1.start();
myThread2.start();
System.out.println("线程没有死锁");
}
}
class MyThread1 extends Thread{
Object o1;
Object o2;
public MyThread1(Object o1,Object o2){
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o1){
synchronized (o2){
}
}
}
}
class MyThreaad2 extends Thread{
Object o1;
Object o2;
public MyThreaad2(Object o1,Object o2){
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o2){
synchronized (o1){
}
}
}
}
会死锁
package com.deadlock.test2;
public class DeadLock2 {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
MyThread1 myThread1 = new MyThread1(o1,o2);
MyThreaad2 myThread2 = new MyThreaad2(o1,o2);
System.out.println("线程准备开始执行");
myThread2.start();
myThread1.start();
System.out.println("线程还在执行,,还没有结束,只是执行到,执行到,执行到,执行经过我这行代码");
}
}
class MyThread1 extends Thread{
Object o1;
Object o2;
public MyThread1(Object o1,Object o2){
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o1){ //synchronized 在开发当中不要嵌套使用,不然可能会导致死锁现象
try {
Thread.sleep(2000);
} catch (InterruptedException e) { //为什么这里加了睡眠就一定死锁
e.printStackTrace();
}
synchronized (o2){
}
}
}
}
class MyThreaad2 extends Thread{
Object o1;
Object o2;
public MyThreaad2(Object o1,Object o2){
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o2){
try {
Thread.sleep(2000);
} catch (InterruptedException e) { //为什么这里加了睡眠就一定死锁
e.printStackTrace();
}
synchronized (o1){
}
}
}
}