Java生产消费模式实例代码[已测试](2)

e.printStackTrace();
            }
        }
        System.out.println("有数据,干活。。。。。");
        notify();
        return thread_pool.removeFirst();

}

}

///////////////////////////////////////// Consumer.java

/**
 * 消费线程
 *
 * @author Mygia.mai
 *
 */
public class Consumer extends Thread {
   
    private QueueThread q;
   
    public Consumer(QueueThread q){
        this.q=q;
    }

public void run() {
        while (true) {
            System.out.println(getName() + " 开始执行消费!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(getName() + q.get());
            System.out.println(getName() + " 消费结束!");
        }
    }
}

////////////////////////////////// Producer.java 生产者线程

public class Producer extends Thread {

QueueThread q;

private String str;

Producer(QueueThread q) {
        this.q = q;
    }

public String getStr() {
        return str;
    }

public void setStr(String str) {
        this.str = str;
    }

public void run() {
        for (int i = 0; i < 50; i++)
            q.put(str + i);
    }

}

////////////////////////////////////////// InitQueue.java 初始化消费线程池

public class InitQueue {

private static QueueThread queue = null;

public InitQueue() {
        synchronized (this) {
            if (queue == null) {
                System.out.println("初始化消费线程队列!启动5条");
                queue = new QueueThread();
                // 启动5条消费线程
                for (int i = 0; i < 5; i++) {
                    Consumer c = new Consumer(queue);
                    c.start();
                }
            }
        }
    }

/**
     * 获取
     * @return
     */
    public QueueThread getQueue() {
        return queue;
    }

}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwsgpf.html