- import java.util.concurrent.locks.*;
- public class Goods {
- private String name;
- private int count = 0;
- private boolean flag = false;
- //定义一个锁
- private final Lock lock = new ReentrantLock();
- //定义生产者持的锁
- private final Condition conditionPro = lock.newCondition();
- //定义消费者持的锁
- private final Condition conditionCon = lock.newCondition();
-
- public void in(String name) throws InterruptedException {
- lock.lock();
- try{
- while(flag)
- conditionPro.await();
- this.name = name + "---" + count++;
- System.out.println(Thread.currentThread().getName() + " 生产 " + this.name);
- flag = true;
复制代码- public class Producer implements Runnable {
- private Goods g;
-
- public Producer(){}
- public Producer(Goods g) {
- this.g = g;
- }
-
- public void run(){
- while(true){
- try{
- g.in("#商品#");
- }
- catch(InterruptedException e){
-
- }
- }
- }
- }
复制代码
- public class Consumer implements Runnable{
- private Goods g;
-
- public Consumer(){}
- public Consumer(Goods g) {
- this.g = g;
- }
-
- public void run(){
- while(true){
- try{
- g.out();
- }
- catch(InterruptedException e){
-
- }
- }
- }
- }
复制代码- public class TestMain {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Goods g = new Goods();
- Producer p = new Producer(g);
- Consumer c = new Consumer(g);
-
- new Thread(p).start();
- new Thread(p).start();
- new Thread(c).start();
- new Thread(c).start();
- }
- }
复制代码
重要的代码写三遍,今天终于可以自己背着写出来了。
|
|