生产者--消费者模式 1、示例:
- package unit18;
- class Resource{
- private String name;
- private int count = 1;
- private Boolean flag = false;
-
- public synchronized void set(String name){
- while(flag){ //while 的巧妙使用:当wait后的线程唤醒时,判断标标记
- try {
- this.wait();//this代表调用函数线程
- } catch (InterruptedException e) {}
- }
-
- this.name = name+"__ " + count++;
- System.out.println(Thread.currentThread().getName()+ "......生产者" + this.name);
- flag = true;
- this.notifyAll();
- }
-
- public synchronized void show(){
- while(!flag){
- try {
- this.wait();
- } catch (InterruptedException e) {
- }
- }
-
-
- System.out.println(Thread.currentThread().getName()+"消费者"+ this.name);
- flag = false;
- this.notifyAll();
- }
- }
- //定义生产类Producter,生产商品
- class Producter implements Runnable{
- private Resource r;
- Producter(Resource r){
- this.r = r;
- }
- public void run(){
- while(true){
- r.set("商品");
- }
- }
- }
- //定义消费者类Customer,消费商品
- class Customer implements Runnable{
- private Resource r;
- Customer(Resource r){
- this.r = r;
- }
- public void run(){
- while(true){
- r.show();
- }
- }
- }
- public class ProductercustomerTest {
- public static void main(String[] args) {
- Resource r = new Resource();
- Producter pro = new Producter(r);
- Customer cus = new Customer(r);
- Thread t1 = new Thread(pro);
- Thread t2 = new Thread(pro);
- Thread t3 = new Thread(cus);
- Thread t4 = new Thread(cus);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码分析: 原因:让被唤醒的线程再次判断标记 原因: 因为需要唤醒对方线程,如果使用notify容易出现值唤醒本方线程的情况,导致线程中所有线程都处于等待状态
|