线程协作,producer and consumer.

from:http://www.java-samples.com/showtutorial.php?tutorialid=306

//Q.java 代表队列,存数据

package com.test.threadcooperate;

//A correct implementation of a producer and consumer. 
public class Q {
	int n;
	volatile boolean valueSet = false;

	public synchronized int get() {
		if (!valueSet)
			try {
				wait(); // 无限等待
				// wait(4000); //每过4秒继续执行一次
			} catch (InterruptedException e) {
				System.out.println("InterruptedException caught");
			}
		System.out.println(Thread.currentThread() + ",ThreadID:"
				+ Thread.currentThread().getId() + " Got: " + n);
		valueSet = false;
		notifyAll();
		return n;
	}

	synchronized void put(int n) {
		if (valueSet)
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("InterruptedException caught");
			}
		this.n = n;
		valueSet = true;
		System.out.println("Put: " + n);
		notifyAll();
	}
}

//producer.java
package com.test.threadcooperate;

public class Producer implements Runnable {
	Q q;

	Producer(Q q) {
		this.q = q;
		new Thread(this, "Producer").start();
	}

	public void run() {
		int i = 0;
//		while (true) {
//			q.put(i++);
//		}
		for(;i<100;) {
			q.put(i++);
		}
		q.put(-1);	//用于退出,状态标志
	}
}

//consumer.java


package com.test.threadcooperate;


public class Consumer implements Runnable {
	Q q;

	Consumer(Q q) {
		this.q = q;
		new Thread(this, "Consumer").start();
	}

	public void run() {
		while (true) {
			 int result= q.get();
			 if(result==-1)break;
		}
	}
}

//PCFixed.java

package com.test.threadcooperate;

public class PCFixed {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Q q = new Q();
		new Producer(q);
		new Consumer(q);	//消费者1
//		new Consumer(q);	//消费者2,有两个消费者时有问题。
		System.out.println("Press Control-C to stop.");
	}
}
posted @ 2011-03-21 14:23  庚武  Views(275)  Comments(0Edit  收藏  举报