Java 线程死锁
精华
小牛编辑
135浏览
2023-03-14
1 什么是Java线程死锁
Java中的死锁是多线程的一部分。当线程正在等待由另一个线程获取的对象锁而第二个线程正在等待由第一个线程获取的对象锁时,可能会发生死锁。由于两个线程都在互相等待释放锁,因此这种情况称为死锁。
2 Java线程死锁的例子
package cn.xnip;
/**
* 小牛知识库网: https://www.xnip.cn
*/
/**
* Java 线程死锁的例子
*/
public class Demo {
public static void main(String[] args) {
final String resource1 = "eric";
final String resource2 = "jack";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
输出结果为:
Thread 1: locked resource 1
Thread 2: locked resource 2