多个同步可能会造成资源不正确或者造成死锁 解决办法有生产者消费者模式的信号灯法
*synchronized同步 指的是多个进程访问同一个资源,为了确保资源的正确性,进行同步
package xidian.lili.threadpro;
/**
*
* 共同的资源是moive
*/
public class Movie {
private String pic;
private boolean flag=true;//一定要初始化 先要生产 才能消费
/**
public Movie(){
}
//播放
public synchronized void play(String pic){
if(!flag){//生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开始生产
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//生产完毕
this.pic=pic;
System.out.println("生产了"+pic);
//通知消费
this.notify();
//生产者停下
this.flag=false;
}
//观看
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开始消费
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//消费完成
System.out.println("消费了"+pic);
//通知生产
this.notify();
//停止消费
this.flag=true;
}
}
/**
*
* 共同的资源是moive
* 访问这个资源的两个线程是Player(生产者)和Wathcher(消费者)
* wait()释放锁 区别于sleep(long time)
* notify() 唤醒进程 必须和synchronized配合使用
*/
public class Movie {
private String pic;
private boolean flag=true;//一定要初始化 先要生产 才能消费
/**
* 信号灯
* flag true 生产者生产 消费者等待 生产完毕 通知消费 生产者停下
* flag false 消费者消费 生产者等待 消费完毕 通知生产 消费者停下
*/
public Movie(){
}
//播放
public synchronized void play(String pic){
if(!flag){//生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开始生产
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//生产完毕
this.pic=pic;
System.out.println("生产了"+pic);
//通知消费
this.notify();
//生产者停下
this.flag=false;
}
//观看
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开始消费
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//消费完成
System.out.println("消费了"+pic);
//通知生产
this.notify();
//停止消费
this.flag=true;
}
}
//生产者
public class Player implements Runnable{private Movie movie;
public Player(Movie m){
this.movie=m;
}
@Override
public void run() {
for(int i=0;i<20;i++){
if(i%2==0)
{
movie.play("你好吗");
}
else{
movie.play("我很好");
}
}
}
}
package xidian.lili.threadpro;
//消费者
public class Watcher implements Runnable {private Movie movie;
public Watcher(Movie m){
this.movie=m;
}
@Override
public void run() {
for(int i=0;i<20;i++){
movie.watch();
}
}
}
package xidian.lili.threadpro;
//主程序 应用
public class App {public static void main(String[] args) {
//创建同一个资源
Movie m=new Movie();
//两个线程
Player p=new Player(m);
Watcher w=new Watcher(m);
new Thread(p).start();
new Thread(w).start();
}
}