线程通信,生产者消费者问题(Java)

在java中,使用wait()和notify()方法实现线程之间的通信,当线程被阻塞无法继续进行时,可以调用wait()方法,他的作用是使线程进入休眠状态,所有的资源被释放,允许其他线程使用,当一个线程释放某种资源时,可以调用notify()方法,使某个进入休眠状态的线程被唤醒,继续执行。notifyAll()可以将所有的线程唤醒,继续执行。

public class ProCus {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Operation p=new Operation();
        new Thread(new Producer(p)).start();
        new Thread(new Consumer(p)).start();
    }

}

class Operation{
    String name="";
    Boolean bfull=false;//对于bfull可以进行设置,来确定仓库的容量是否满了
    public synchronized void put(String name){
        this.name=name;
        if(bfull)
        try{
            wait();
            Thread.sleep(1000);
        }catch(Exception e){}
        System.out.println(name+"生产一个产品");
        bfull=true;
        notify();
    }
    public synchronized void get(){
        if(!bfull)
            try{
                wait();
            }catch(Exception e){}
            System.out.println("顾客取走一个产品");
            bfull=false;
            notify();
    }
}
//实现Runnable接口,run()方法是为程序中并发执行的线程建立的进入点
class Producer implements Runnable{
    Operation p;
    public Producer(Operation p){
        this.p=p;
    }
    
    public void run(){
        int i=0;
        while(true){
            if(i==0)
                p.put("Kellerman");
            else p.put("Kim");
            i=1-i;
        }
    }
}


class Consumer implements Runnable{
    Operation p;
    public Consumer(Operation p){
        this.p=p;
    }
    public void run(){
        while(true){
            p.get();
        }
    }
}
原文地址:https://www.cnblogs.com/redlight/p/2531554.html