package dome3;
/**
* 模式:生产者 -- 消费者模式
* 引入模拟电影院情景(播放什么,观众看什么)
* @author lzd
*
*/
public class movies {
private String pic;
private boolean flag = true ;
/**
*
* @param pic : 传入String 类型参数,表示传入的电影
*/
public synchronized void play (String pic)
{
if (!flag)
{
try {
this .wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500 );
} catch (InterruptedException e) {
e.printStackTrace();
}
this .pic = pic;
System.out.println("producer: " + pic);
this .notify();
flag = !flag;
}
public synchronized void watcher ()
{
if (flag)
{
try {
this .wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(200 );
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("customer: " + pic);
this .notifyAll();
flag = !flag;
}
}
package dome3;
/**
* 播放线程
* @author lzd
*
*/
public class Player implements Runnable {
private movies movies1;
public Player (movies movies1) {
this .movies1 = movies1;
}
@Override
public void run () {
for (int i = 1 ; i <= 20 ; i++)
if (i%2 ==0 )
movies1.play("左青龙" );
else {
movies1.play("右白虎" );
}
}
}
package dome3;
/**
* 观看线程
* @author lzd
*
*/
public class Watcher implements Runnable {
private movies movies1;
public Watcher (movies movies1) {
this .movies1 = movies1;
}
@Override
public void run () {
for (int i = 1 ; i <= 20 ; i++)
movies1.watcher();
}
}
package dome3;
/**
* 主函数
* @author lzd
*
*/
public class App {
public static void main (String[] args) {
movies m = new movies();
Player p = new Player(m);
Watcher w = new Watcher(m);
Thread producer = new Thread(p);
Thread customer = new Thread(w);
producer.start();
customer.start();
}
}