线程间通信-多生产者多消费者问题

package com.huaWei.threadCommunication;

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

/**
 * 资源
 * 
 * @author 华伟科技
 * 
 */
public class Resource {
private String name;
private int count = 1;
private boolean flag = false;
// wait和sleep区别?
// 1、wait可以指定时间也可以不指定,sleep必须指定时间。
// 2、在同步中时,对cpu的执行权和锁的处理不同。
//    wait:释放执行权,释放锁。
//    sleep:释放执行权,不释放锁。
// jdk1.5以后将同步和锁封装成了对象。并将操作锁的隐式方式定义到了该对象中,将隐式动作变成显示动作。
// jdk1.5以后Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。
//Lock接口:出现替代了同步代码块或者同步函数。将同步的隐式锁操作变成显示锁操作。同时更为灵活。可以一个锁上加上多组监视器。
//lock():获取锁。
//unlock():释放锁,通常需要定义finally代码块中。
//Condition接口:出现替代了Object中的wait、notify、notifyAll方法。将这些监视器方法单独进行了封装,变成Condition监视器对象。可以任意锁进行组合。
// await();signal();signalAll();
// 创建一个锁对象。
final Lock lock = new ReentrantLock();
// 通过已有锁获取该锁上的监视器对象。
// final Condition condition = lock.newCondition();
// 通过已有的锁获取两组监视器,一组监视生产者,一组监视消费
final Condition producerCondition = lock.newCondition();
final Condition consumerCondition = lock.newCondition();


// 【同步代码块】,对于锁的操作是隐式的。如:synchronized(obj){.....}
public/* synchronized */void set(String name) {
// 获取锁
lock.lock();
try {
// if判断标记,只有一次,会导致不该运行的线程运行了。出现了数据错误的情况。
// while判断标记,解决了线程获取执行权后,是否要运行!
while (this.flag)
try {
// this.wait();
// condition.await();
producerCondition.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name = name + count;
count++;
System.out.println(Thread.currentThread().getName() + "-------生产者------->" + this.name);
this.flag = true;
// notify:只能唤醒一个线程,如果本方唤醒本方,没有意义。而且while判断标记 + notify会导致死锁。
// notifyAll:解决了本方线程一定会唤醒对方线程的问题。
// this.notifyAll();//效率低
// condition.signalAll();
consumerCondition.signal();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
// 释放锁
lock.unlock();
}
}

public/* synchronized */void out() {
// 获取锁
lock.lock();
try {
// if判断标记,只有一次,会导致不该运行的线程运行了。出现了数据错误的情况。
// while判断标记,解决了线程获取执行权后,是否要运行!
while (!this.flag) {
try {
// this.wait();
// condition.await();
consumerCondition.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "===========消费者===========>" + this.name);
this.flag = false;
// notify:只能唤醒一个线程,如果本方唤醒本方,没有意义。而且while判断标记 + notify会导致死锁。
// notifyAll:解决了本方线程一定会唤醒对方线程的问题。
// this.notifyAll();//效率低
// condition.signalAll();
producerCondition.signal();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
// 释放锁
lock.unlock();
}
}

}

package com.huaWei.threadCommunication;


/**
 * 生产者
 * 
 * @author 华伟科技
 * 
 */
public class Producer implements Runnable {
private Resource resource;


public Producer(Resource resource) {
this.resource = resource;
}


@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
resource.set("烤鸭");
}
}

}

package com.huaWei.threadCommunication;


/**
 * 消费者
 * 
 * @author 华伟科技
 * 
 */
public class Consumer implements Runnable {
private Resource resource;


public Consumer(Resource resource) {
this.resource = resource;
}

@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
resource.out();
}
}

}

package com.huaWei.threadCommunication;


/**
 * 多生产与多消费的多线程测试
 * 
 * @author 华伟科技
 * 
 */
public class ProducerConsumerThreadMain {

public static void main(String[] args) {

// 创建资源
Resource resource = new Resource();
// 创建任务
Producer producer = new Producer(resource);
Consumer consumer = new Consumer(resource);
// 创建线程,执行路径
Thread thread0 = new Thread(producer);
Thread thread1 = new Thread(producer);
Thread thread2 = new Thread(consumer);
Thread thread3 = new Thread(consumer);
// 开启线程
thread0.start();
thread1.start();
thread2.start();
thread3.start();

}
}

package com.huaWei.threadCommunication;


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


public class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();


final Object[] items = new Object[100];
int putptr, takeptr, count;// 存,取,计数器,用于操作数组的变量


public void put(Object x) throws InterruptedException {
lock.lock();
try {
// 判断条件一定要使用while,因为安全。
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length)
putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}


public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length)
takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值