生产者与消费者

package ten;
// 生产者 消费者
/*public class sx {
public static void main(String[] args) {
// 创建资源
Res r=new Res();
// 创建两个任务
Producer p=new Producer(r);
Consumer c=new Consumer(r);
// 创建线程
Thread t0=new Thread(p,"A");
Thread t1=new Thread(p,"B");
Thread t2=new Thread(c,"C");
Thread t3=new Thread(c,"D");

t0.start();
t1.start();
t2.start();
t3.start();
}
}
class Res{
private String name;
private int count=1;
// 定义标记
private boolean flag;

// 提供给商品赋值的方法
public synchronized void set(String name){

while(flag){//判定标记为true,执行wait.等待为flag,就生产
try{
this.wait();
}catch(Exception e){}
}
this.name=name+"---"+count;//面包1 面包2 面包3
count++;//2 3 4
System.out.println(Thread.currentThread().getName()+"。。。生产者。。。"+name+count);
//生产完毕 将标记为true
flag=true;
//唤醒所有等待线程(包括本方线程)
this.notifyAll();
//提供一个获取商品方法
}
public synchronized void get(){

while(!flag){
try{this.wait();
}catch (Exception e) {}
}
System.out.println(Thread.currentThread().getName()+"...消费者...."+this.name);
//将标记 改为 false
flag =false;
//唤醒所有等待线程(包括本方线程)
this.notifyAll();
}
}
//生产者
class Producer implements Runnable{
private Res r;
Producer(Res r){
this.r=r;
}
public void run(){
while(true)
r.set("面包");
}
}
//消费者
class Consumer implements Runnable{
private Res r;
Consumer(Res r){
this.r=r;
}
public void run(){
while(true)
r.get();
}
}*/
public class sx {
public static void main(String[] args) {
zx c=new zx("面包");
s s1=new s(c);
x x1=new x(c);
Thread t1=new Thread(s1);
Thread t2=new Thread(s1);
Thread t3=new Thread(x1);
Thread t4=new Thread(x1);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class zx{
private String name;
private int a=0;
private boolean flag;
zx(String name){
this.name=name;
}

public synchronized void sheng(){
while(flag)
try{
this.wait();
}catch (Exception e) {}
this.name=name+"----"+a;

System.out.println(Thread.currentThread().getName()+"生产者----"+a);
a++;
flag=true;
this.notifyAll();
}
public synchronized void xiao(){
while(!flag)
try{
this.wait();
}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"消费者---"+this.name);
flag=false;
this.notifyAll();
}
}
class s implements Runnable{
private zx r;
s(zx r){
this.r=r;
}
public void run(){
while(true)
r.sheng();
}
}
class x implements Runnable{
private zx r;
x(zx r){
this.r=r;
}
public void run(){
while(true)
r.xiao();
}
}

 

posted @ 2017-12-25 10:38  zhouwen周文  阅读(78)  评论(0编辑  收藏  举报