Java中死锁及解决办法

死锁:过多的同步容易造成死锁

解决方法:可以用生产者——消费者模式解决

1)资源

//flag=true 生产者生产 消费者等待
//flag=false 生产者等待 消费者消费
//
public class Movie {
private String pic;
private boolean flag=true;

public synchronized void play(String pic) {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(“生产:”+pic);
this.pic=pic;
this.notify();
this.flag = false;
}
public synchronized void watch() {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(“消费”+pic);
this.notify();
this.flag = true;
}
}

2)生产者

public class Player implements Runnable {
private Movie m;
public Player(Movie m) {
super();
this.m = m;
}
public void run() {
for (int i = 0; i < 20; i++) {
if(i%2==0) {
m.play(“电影”);
}else {
m.play(“电视剧”);
}
}
}
 {

}
}

3)消费者

public class Watcher implements Runnable {

private Movie m;

public Watcher(Movie m) {
super();
this.m = m;
}

@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i <20; i++) {
m.watch();
}
}

}

    原文作者:java锁
    原文地址: https://blog.csdn.net/qq_38208023/article/details/79216336
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞