死锁及解决方案
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了死锁及解决方案相关的知识,希望对你有一定的参考价值。
死锁:t1线程和t2线程各自占有共享资源o1,o2,互相在等待对方释放资源,这样形成的两个线程互相等待,无法继续运行的"死锁"状态.
解决方案:同一个代码块,不能持有两个对象锁.
package DeadLock;
public class DeadLockUse {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
Thread t1 = new MyThread1(o1,o2);
Thread t2 = new MyThread2(o1,o2);
t1.start();
t2.start();
}
}
class MyThread1 extends Thread{
Object o1;
Object o2;
public MyThread1(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
public void run() {
synchronized(o1) {
try {
Thread.sleep(1000*3);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
synchronized(o2) {
System.out.println("死锁解决了1!");
}
}
}
}
class MyThread2 extends Thread{
Object o1;
Object o2;
public MyThread2(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
public void run() {
synchronized(o2) {
try {
Thread.sleep(3*1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
synchronized(o1) {
System.out.println("死锁解决了2!");
}
}
}
}
解决方法:
package DeadLock;
public class DeadLockUse {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
Thread t1 = new MyThread1(o1,o2);
Thread t2 = new MyThread2(o1,o2);
t1.start();
t2.start();
}
}
class MyThread1 extends Thread{
Object o1;
Object o2;
public MyThread1(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
public void run() {
synchronized(o1) {
try {
Thread.sleep(1000*3);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
synchronized(o2) {
System.out.println("死锁解决了1!");
}
}
}
class MyThread2 extends Thread{
Object o1;
Object o2;
public MyThread2(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
public void run() {
synchronized(o2) {
try {
Thread.sleep(3*1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
synchronized(o1) {
System.out.println("死锁解决了2!");
}
}
}
运行结果
以上是关于死锁及解决方案的主要内容,如果未能解决你的问题,请参考以下文章