码迷,mamicode.com
首页 > 编程语言 > 详细

Java基础之线程5-线程同步死锁

时间:2020-05-11 23:18:29      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:static   catch   inter   zed   dead   int   sys   try   cep   

死锁:线程之间因条件相互竞争,导致线程都不能正常执行完,从而产生了死锁。

 

死锁的例子:

 

public class TestDeadLock implements Runnable {
public int flag = 1;
static Object o1 = new Object(), o2 = new Object();

@Override
public void run() {
System.out.println("flag = " + flag);
if (flag == 1){
synchronized (o1){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

synchronized (o2){
System.out.println("1");
}
}
}

if (flag == 0){
synchronized (o2){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

synchronized (o1){
System.out.println("0");
}
}
}
}

public static void main(String[] args) {
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;

Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);

t1.start();
t2.start();

}
}

Java基础之线程5-线程同步死锁

标签:static   catch   inter   zed   dead   int   sys   try   cep   

原文地址:https://www.cnblogs.com/risuschen/p/12872778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!