标签:
class Producer implements Runnable { private final Queue<Task> queue; private final static int MAX_SIZE = 200; Producer(Queue<Task> q) { queue = q; } public void run() { synchronized (queue) { //如果缓冲区满,该线程释放queue锁,等待 if (queue.size() >= MAX_SIZE) { try { queue.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //如果缓冲区不满,则继续添加任务 queue.add(new Task()); System.out.println("增加了一个任务,当前任务总数为" + queue.size()); //添加任务以后,通知所有处于等待状态的线程 queue.notifyAll(); } } } public class ProducerTimerTask extends TimerTask { private final Queue<Task> queue; ProducerTimerTask(Queue<Task> q) { queue = q; } @Override public void run() { Producer p = new Producer(queue); new Thread(p).start(); } } class Consumer implements Runnable { private final Queue<Task> queue; Consumer(Queue<Task> q) { queue = q; } public void run() { while (true) { synchronized (queue) { //如果缓冲区内为空,消费者释放queue对象锁,处于等待状态 if (queue.size() <= 0) { try { queue.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //如果缓冲区不为空,消费者将队首元素取走 queue.remove(); System.out.println("执行了一个任务,剩余任务总数为" + queue.size()); //取走后通知所有处于等待状态的线程 queue.notifyAll(); } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public class ConsumerTimerTask extends TimerTask { private final Queue<Task> queue; ConsumerTimerTask(Queue<Task> q) { queue = q; } @Override public void run() { Consumer c = new Consumer(queue); new Thread(c).start(); } } class Setup { public static void main(String args[]) { Queue<Task> taskQueue = new LinkedList<Task>(); Timer timer = new Timer(); timer.schedule(new ProducerTimerTask(taskQueue), 0, 1000); Consumer c = new Consumer(taskQueue); new Thread(c).start(); } } public class Task { }
标签:
原文地址:http://www.cnblogs.com/mu-tou-man/p/4840922.html