具体代码如:
/**
* Project: ali
*
* File Created at 2011-1-12
* $Id$
*
* Copyright 2008 Alibaba.com Croporation Limited.
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Alibaba Company. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Alibaba.com.
*/
package wait;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* 生产者与消费者模式
*/
public class Wait {
Queue<Integer> queue = new LinkedBlockingQueue<Integer>();
final static int MAX = 1000000000;
public static void main(String[] a) {
new Wait().start();
}
void start() {
Thread produce = new Thread(new Produce());
produce.start();
Thread consume = new Thread(new Consume());
consume.start();
Thread monitor = new Thread(new Monitor());
monitor.start();
System.out.println("exit");
}
/**
* 生产者线程
*/
class Produce implements Runnable {
public void run() {
for (int i = 0; i < 5691782; i++) {
synchronized (queue) {
queue.add(i);
queue.notify();
if (queue.size() >= MAX)
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 消费者类 <br>
* 注意: 在进入Object.wait()之前一家要判断条件是否满足,
* 在对队列进行操作的时候应该一次性将数据全部消化(可以交给其它线程处理),然后在由生产队列加入数据
*/
class Consume implements Runnable {
@Override
public void run() {
synchronized (queue) {
while (true) {
if (queue.isEmpty())
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (queue.size() < MAX)
queue.notify();
//此处消费内容,
System.out.println(queue.size() + "===" + queue.poll());
}
}
}
}
/**
* 监控线程,查看队列中还有多少未处理数据.
*/
class Monitor implements Runnable {
public void run() {
while (true) {
System.out.println("队列中数据量:" + queue.size());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}