生产者消费者

    xiaoxiao2021-03-25  8

    package thread_communication; /* * * notify之后和正常线程一样有资格竞争执行权; * * * * * * * */ class Resource{ private String name; private int num=1; private boolean mark=false; public synchronized void pro(String name){ while(mark){//保证不会生产两次消费一次 try{this.wait();}catch(Exception e){} } this.name=name+" ,"+num++; System.out.println(Thread.currentThread().getName()+" produce comodity: "+this.name); mark=true; this.notifyAll();//notify往往唤醒第一个,会导致唤醒本方,而notifyAll会解决这个问题 } public synchronized void print(){ while(!mark){//保证不会消费两次生产一次 try{this.wait();}catch(Exception e){} } System.out.println(Thread.currentThread().getName()+"consume comodity: "+name); mark=false; this.notifyAll(); } } class producer implements Runnable{ Resource r; producer(Resource r){ this.r=r; } public void run(){ while(true){ r.pro("bag"); } } } class consumer implements Runnable{ Resource r; consumer(Resource r){ this.r=r; } public void run(){ while(true){ r.print(); } } } public class Producer_Customer { public static void main(String[] args) { Resource rr=new Resource(); consumer c=new consumer(rr); producer p=new producer(rr); Thread t1=new Thread(c); Thread t2=new Thread(c); Thread t3=new Thread(p); Thread t4=new Thread(p); t1.start(); t2.start(); t3.start(); t4.start(); } }
    转载请注明原文地址: https://ju.6miu.com/read-200120.html

    最新回复(0)