线程的生产者消费者问题

package xiancheng;
/**
* wait() 等待 ,释放锁 sleep 不释放锁
* @author User
*
*/

public class lianxi20 {
//t 生产者生产 通知消费 f 消费者消费 通知生产
private boolean flag=true;
//模拟生产的物品
private String picString;
//生产
public synchronized void play(String picString){
//当flag为false状态,是生产者停止工作,进入等待状态
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//模拟生产时间
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//执行生产
this.picString=picString;

//通知消费
this.notifyAll();
//生产者停下
this.flag=false;


}
//消费
public synchronized void watch(){
//当flag为true 消费者停止等待 进入等待状态
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//模拟消费过程
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//进行消费操作
System.out.println(picString);
//通知生产
this.notify();
//消费者停止
this.flag=true;
}

}

 

/**
* 生产者
* @author User
*
*/
public class lianxi21 implements Runnable{
//定义资源
private lianxi20 m;
//定义含参构造器
public lianxi21(lianxi20 m) {
this.m = m;
}
//重写run方法 进行生产操作
@Override
public void run() {
for(int i=0;i<20;i++){
if (0==i%2) {
m.play("傻光");
}else {
m.play("春光");
}
}
}

}

 

 

/**
* 消费者
* @author User
*
*/
public class lianxi22 implements Runnable{
//定义资源
private lianxi20 m;
//定义含参构造器
public lianxi22(lianxi20 m) {
this.m = m;
}
//重写run方法,线程执行是进行watch操作
@Override
public void run() {
for(int i=0;i<20;i++){
m.watch();
}
}

}

 

public class lianxi23 {
public static void main(String[] args) {
//共同的资源
lianxi20 m=new lianxi20();
//定义生产者
lianxi21 p=new lianxi21(m);
//定义生产者
lianxi22 w=new lianxi22(m);
//线程进行
new Thread(p).start();
new Thread(w).start();
}

}

 

通过解决生产者消费者问题实现多线程的顺序执行问题..

posted @ 2017-05-17 21:16  Dark~Clearlove  阅读(154)  评论(0编辑  收藏  举报