您的位置:首页 > 编程语言 > Java开发

Java线程同步:生产者-消费者 模型(代码示例)

2015-02-13 21:17 716 查看
public class ThreadSyn {
	
	public static void main(String[] args) {
		new ThreadSyn();
	}

	public ThreadSyn() {
		Queue queue = new Queue();

		Producter p = new Producter(queue);
		Consumer c = new Consumer(queue);

		p.start();
		c.start();
	}

	
	// Queue模拟Java线程同步中的生产者消费者仓库、队列。
	private class Queue {
		int value; // 为了使例子简单,value即为假设长度为1的仓库、队列
		boolean full = false;

		public synchronized void put(int i) {
			if (!full) {
				value = i;
				full = true;

				notify();
			}

			try {
				wait();
			} catch (InterruptedException e) {
				// e.printStackTrace();
			}
		}

		public synchronized int get() {
			if (!full)
				try {
					wait();
				} catch (InterruptedException e) {
					// e.printStackTrace();
				}

			full = false;

			notify();

			return value;
		}
	}

	
	// Java线程同步模型-生产者
	private class Producter extends Thread {
		private Queue q;

		public Producter(Queue q) {
			this.q = q;
		}

		public void run() {
			for (int i = 0; i < 20; i++) {
				System.out.println("生产了:" + i);
				q.put(i);
			}
		}
	}

	// Java线程同步模型-消费者
	private class Consumer extends Thread {
		private Queue q;

		public Consumer(Queue q) {
			this.q = q;
		}

		public void run() {
			while (true) {
				System.out.println("消费了:" + q.get());
			}
		}
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: