package com.heima.code;
/*
死锁:
同步中嵌套同步。
面试中请写一个死锁程序。
(能写出死锁,就代表已经理解了死锁,在程序开发中就会避免死锁)
* */
class TicketTest implements Runnable {
private boolean flag;
TicketTest(boolean flag){
this.flag = flag;
}
@Override
public void run() {
if(flag){
while(true){
synchronized (MyLock.lockA) {
System.out.println("if lockA");
synchronized (MyLock.lockB) {
System.out.println("if lockB");
}
}
}
}else{
while(true){
synchronized (MyLock.lockB) {
System.out.println("else lockB");
synchronized (MyLock.lockA) {
System.out.println("else lockA");
}
}
}
}
}
}
class MyLock{
static Object lockA = new Object();
static Object lockB = new Object();
}
public class ThreadDemo07 {
public static void main(String[] args) {
Thread t1 = new Thread(new TicketTest(true));
Thread t2 = new Thread(new TicketTest(false));
t1.start();
t2.start();
}
}
|
|