一,介绍
二,Demo案例
1.Move.java(相当于生产者生产的对象和消费者消费的对象,即两个线程共享的对象)
package com.geminno.thread;
public class Movie {
private String pic;
private boolean flag = true;
public Movie(String pic) {
super();
this.pic = pic;
}
public Movie() {
super();
// TODO Auto-generated constructor stub
}
public synchronized void play(String pic){
if(!flag){ // 如果flag 是false,停下不生产
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 开始生产
/*try {
Thread.sleep(300);
} 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){//如果flag是true ,停止观看
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.notifyAll();
//改变信号灯
this.flag = true;
}
}
2.生产者线程对象(Player.java)
package com.geminno.thread;
public class Player implements Runnable {
Movie m ;
public Player(Movie m) {
super();
this.m = m;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if(i % 2 == 0){
m.play("倚天屠龙记");
}else {
m.play("简爱");
}
}
}
}
3.消费者线程(watcher.java)
package com.geminno.thread;
public class Watcher implements Runnable{
Movie m ;
public Watcher(Movie m) {
super();
this.m = m;
}
@Override
public void run() {
for(int i=0;i<20;i++){
m.watch();
}
}
}
4.测试程序(App.java)
package com.geminno.thread;
public class App {
public static void main(String[] args) {
Movie m = new Movie();
Player player = new Player(m);
new Thread(player).start();
Watcher watcher = new Watcher(m);
new Thread(watcher).start();
}
}
352




被折叠的 条评论
为什么被折叠?



