Java多线程经典问题之生产者消费者模式

1.线程共享的类:

package cn.skh.producter;
/**
 * 一个场景 共同的资源
 * 生产者消费者模式 信号灯法
 * @author SKH&L
 *
 */
public class Movie {
   private String str;
   private boolean flag=true;
   //信号灯
   //true 生产者生产;
   //false 消费;
   public synchronized void play(String str) {
	   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();
	}
	   //生产完毕
	   this.str=str;
	   //通知消费
	   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(500);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	   System.out.println(str);
	   //通知生产
	   this.notify();
	   //停止消费
	   this.flag=true;
   }
}

2.消费者(Player)&&消费者(Watcher)

package cn.skh.producter;

public class Player implements Runnable{
     private Movie m;
     public Player(Movie m) {
    	 super();
    	 this.m=m;
     }
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0;i<10;i++) {
			if(i%2==0)
				m.play("beauty");
			else
				m.play("skh");
		}
	}
}
/*/*/*/*/*/*/*/*/*/*/*/*
package cn.skh.producter;

public class Watcher implements Runnable {
	private Movie m;
    public Watcher(Movie m) {
   	 super();
   	 this.m=m;
    }
	public void run() {
		for(int i=0;i<10;i++)
	   m.watch();
	}
}

3.测试类:

package cn.skh.producter;
public class TestApp {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Movie m=new Movie();
        Player p=new Player(m);
        Watcher w=new Watcher(m);
        new Thread(p).start();
        new Thread(w).start();
	}
}

运行结果:

beauty
skh
beauty
skh
beauty
skh
beauty
skh
beauty
skh

 

你可能感兴趣的:(JAVA)