现在的位置: 首页 > 综合 > 正文

多线程案例:生产者与消费者

2013年10月02日 ⁄ 综合 ⁄ 共 1902字 ⁄ 字号 评论关闭
package info.dyndns.oszc.product;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 这是一个模拟生产者和消费者的案例,使用多线程操作此资源可以加快其处理能力
 * 里面有get和set方法,分别代表获取资源和生产资源
 * 生产-->生产挂起&唤醒消费线程-->消费-->消费挂起&唤醒生产
 * 
 * 
 * @author ZC
 *
 */
public class Product {
	private int id;
	private boolean flag = false;
	private Lock lock = new ReentrantLock();
	private Condition noData = lock.newCondition();
	private Condition gotData = lock.newCondition();

	public void getId() throws InterruptedException {
		try {

			lock.lock();
			while (!flag)
				noData.await();
			System.out.println(Thread.currentThread().getName()+"..消费..." + id);
			flag = false;
			gotData.signal();
		} finally {
			lock.unlock();
		}
	}

	public void setId() throws InterruptedException {
		try {
			lock.lock();
			while (flag)
				gotData.await();
			id++;
			System.out.println(Thread.currentThread().getName()+"..生产......" + id);
			flag = true;
			noData.signal();
		} finally {
			lock.unlock();
		}
	}

}
package info.dyndns.oszc.consumer;

import info.dyndns.oszc.product.Product;

public class Consumer implements Runnable {

	Product product;

	public Consumer(Product val) {
		product = val;
	}

	@Override
	public void run() {
			while (true){
				try {
					product.getId();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
	}

}

package info.dyndns.oszc.producer;

import info.dyndns.oszc.product.Product;

public class Producer implements Runnable{
	private Product p;

	public Producer(Product p) {
		super();
		this.p = p;
	}

	@Override
	public void run() {
		while (true){
			try {
				p.setId();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
}

package info.dyndns.oszc.test;

import info.dyndns.oszc.consumer.Consumer;
import info.dyndns.oszc.producer.*;
import info.dyndns.oszc.product.Product;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Product p =  new Product();
		Consumer consumer = new Consumer(p);
		Producer producer= new Producer(p);
		new Thread(consumer).start();
		new Thread(consumer).start();
		new Thread(producer).start();
		new Thread(producer).start();

	}

}

程序把所有对资源操作的方法写在资源里面了,相对来说比较简洁,也可以考虑提供对外操作变量方法,在runnable方法中修改,但是稍显麻烦。

抱歉!评论已关闭.