//死锁:多个线程互相抱着对方需要的资源,然后形成僵持。
public class Demo1 {
//主方法
public static void main(String[] args) {
Makeup makeup1 = new Makeup(0,"灰姑娘");
Makeup makeup2 = new Makeup(1,"白雪公主");
//启动
makeup1.start ();
makeup2.start ();
}
}
//化妆品
class lipstick{
}
//镜子
class Mirror{
}
//化妆
class Makeup extends Thread {
//需要的资源只有一份,用static来保证只有一份
static lipstick lipstick = new lipstick (); //new化妆品
static Mirror Mirror = new Mirror (); //new镜子
int choice;//选择
String qirname;//使用化妆品的人
Makeup(int choice, String qirname) {
this.choice = choice;
this.qirname = qirname;
}
@Override
public void run() {
//化妆
try {
makeup ();
} catch (InterruptedException e) { //捕获异常
e.printStackTrace ();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) { //获得口红的锁
System.out.println (this.qirname+"获得口红的锁 ");
Thread.sleep (1000);
}
synchronized (Mirror){ //一秒钟获到镜子
System.out.println (this.qirname+"获得镜子的锁 ");
}
}else{
synchronized (Mirror) { //获得镜子的锁
System.out.println (this.qirname+"获得镜子的锁");
Thread.sleep (2000);
}
synchronized (lipstick){ //一秒钟获到镜子
System.out.println (this.qirname+"获得口红的锁");
}
}
}
}
多线程死锁案例
最新推荐文章于 2023-04-06 10:34:27 发布