java线程同步的死锁_Java基础之线程5-线程同步死锁
死鎖:線程之間因條件相互競爭,導(dǎo)致線程都不能正常執(zhí)行完,從而產(chǎn)生了死鎖。
死鎖的例子:
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();
}
}
總結(jié)
以上是生活随笔為你收集整理的java线程同步的死锁_Java基础之线程5-线程同步死锁的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java保存图片进度条_Java上传文件
- 下一篇: java方法和变量修饰符有哪些_死磕Ja