java160110ProducerConsumerDemo2

/**
 * jdk1.5中提供多线程的升级解决方案,将同步替换成Lock操作
 */
package java160110;


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


/**
 * @author LiZheng
 *
 */
public class ProducerConsumerDemo2 {


/**
* @param args
*/
public static void main(String[] args) {
Resource2 resource = new Resource2();
Producer2 producer = new Producer2(resource);
Consumer2 consumer = new Consumer2(resource);
Thread thread1 = new Thread(producer);
Thread thread2 = new Thread(producer);
Thread thread3 = new Thread(consumer);
Thread thread4 = new Thread(consumer);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}


}


//再次升级
class Resource2 {
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();


private Condition conditionCon = lock.newCondition();


private Condition conditionPro =lock.newCondition();

// t1 t2
public void set(String name) throws InterruptedException {
lock.lock(); // 上锁
try {


while (flag) {


// condition.await(); // 线程等待
conditionPro.await();
}
// 将if 改成while后发生全部等待的情况
this.name = name + "---" + count++;
System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name);
flag = true;


// condition.signal(); // 唤醒一个
// condition.signalAll();//仍然是唤醒本方

conditionCon.signal();
} finally {


lock.unlock();// 释放锁
}


}


public void out() throws InterruptedException {
lock.lock();
try {
while (!flag) {
conditionCon.await();
}


System.out.println(Thread.currentThread().getName() + "...消费者......." + this.name);
flag = false;

// condition.signal();
// condition.signalAll();
conditionPro.signal();
} finally {
lock.unlock();
}


}


}


class Producer2 implements Runnable {
private Resource2 resource;


public Producer2(Resource2 resource) {
this.resource = resource;
}


@Override
public void run() {


while (true) {
try {
resource.set("+++商品++++");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


class Consumer2 implements Runnable {
private Resource2 resource;


public Consumer2(Resource2 resource) {
this.resource = resource;
}


@Override
public void run() {


while (true) {
try {
resource.out();
} catch (InterruptedException e) {

e.printStackTrace();
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值