死锁
代码演示
public class DeadLock {
public static void main(String[] args) {
Makeup g1=new Makeup(0, "灰姑凉");
Makeup g2=new Makeup(1, "白雪公主");
g1.start();
g2.start();
}
}
class Lipstick {
}
class Mirror {
}
class Makeup extends Thread {
static Lipstick lip = new Lipstick();
static Mirror mirror = new Mirror();
int choice;
String grilName;
public Makeup(int choice, String grilName) {
this.choice = choice;
this.grilName = grilName;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void makeup() throws InterruptedException {
if(choice==0) {
synchronized (lip) {
System.out.println(this.grilName+"获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror) {
System.out.println(this.grilName+"获得镜子的锁");
Thread.sleep(1000);
}
}else {
synchronized (mirror) {
System.out.println(this.grilName+"获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lip) {
System.out.println(this.grilName+"获得口红的锁");
Thread.sleep(1000);
}
}
}
}
死锁避免方法
Lock锁
代码演示
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
TestLock2 t = new TestLock2();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class TestLock2 implements Runnable {
int ticketNums = 10;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock();
if (ticketNums > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
} else {
break;
}
} finally {
lock.unlock();
}
}
}
}