标签:generated cond on() nbsp nts 同步 ring package sign
前两篇的生产者与消费者(多线程)运用的是synchronized进行同步锁的,本次将运用JDK1.5提供的Lock锁。
它 将synchronized替换成了Lock将Object中的wait notify notifyAll替换成了Condition对象,
Condition可以被Lock获取,
可以创建多个Condition对象,只唤醒对方操作。
具体代码如下:
package cn.zz;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Resource3 {
	private String name;
	private int count;
	private boolean flag = false;
	private Lock lock = new ReentrantLock();
	Condition condition_Pro = lock.newCondition();
	Condition condition_Con = lock.newCondition();
	public void set(String name) throws Exception {
		lock.lock();
		try {
			while (flag) {
				condition_Pro.await();
				this.name = name + "..." + count++;
				System.out.println(Thread.currentThread().getName() + "...生产者"
						+ this.name);
				flag = true;
			}
		} finally {
			condition_Con.signal();
		}
	}
	public void out() throws Exception {
		lock.lock();
		try {
			while (!flag) {
				condition_Pro.await();
				this.name = name + "..." + count++;
				System.out.println(Thread.currentThread().getName()
						+ "...消费者....." + this.name);
				flag = false;
			}
		} finally {
			condition_Pro.signal();
		}
}
	class Producer3 implements Runnable {
		Resource3 res3;
		public Producer3(Resource3 res3) {
			this.res3 = res3;
		}
		@Override
		public void run() {
			while (true) {
				try {
					res3.set("商品");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
}
}
	class Consumer3 implements Runnable {
		Resource3 res3;
		public Consumer3(Resource3 res3) {
			this.res3 = res3;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				try {
					res3.out();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
}
	public class ProducerAndConsumer3 {
		public void main(String[] args) {
			Resource2 res2 = new Resource2();
			new Thread(new Producer2(res2)).start();
			new Thread(new Producer2(res2)).start();
			new Thread(new Consumer2(res2)).start();
			new Thread(new Consumer2(res2)).start();
		}
	}
}

运行结果如上。
标签:generated cond on() nbsp nts 同步 ring package sign
原文地址:https://www.cnblogs.com/twqwe/p/9749927.html