使用wait,notify
package com.tju.edu.frank;
//多生产者多消费者问题
//if判断标记,只有一次,会导致不该运行的线程运行了(即同阵营重复运行,造成多生产单消费,或单生产多消费问题)。出现了数据错误的情况。
//while判断标记,解决了线程获取执行权后,是否要运行(解决了上述问题)
//notify:只能唤醒一个线程,如果本方唤醒了本方线程,没有意义。而且while判断标记+notify会导致死锁。
//notifyAll解决了上述问题,一定会唤醒对方阵营线程
//尽管这样做解决了问题,但是有弊端,因为notifyAll可能会唤醒不必要的线程,就是说会连本放阵营线程一起唤醒(然后这些线程因为while还得回去判断标记),造成的不必要的性能损失
public class ProducerConsumerDemo {
public static void main(String[] args) {
Resource1 r = new Resource1();
Producer p = new Producer(r);
Consumer c = new Consumer(r);
//两个生产者两个消费者
Thread t0 = new Thread(p);
Thread t1 = new Thread(p);
Thread t2= new Thread(c);
Thread t3 = new Thread(c);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
class Producer implements Runnable{
private Resource1 r;
Producer(Resource1 r){
this.r = r;
}
@Override
public void run() {
while(true) {
r.set("飞机");
}
}
}
class Consumer implements Runnable{
private Resource1 r;
Consumer(Resource1 r){
this.r = r;
}
@Override
public void run() {
while(true) {
r.out();
}
}
}
//使用notify可能会导致唤醒的是同一阵营线程(经过while判断再次休眠),当对方阵营全休眠时
//这时所有线程都休眠,无人进行唤醒操作,造成死锁
//为解决这种现象(也就是保证唤醒的是对方阵营),只能用notifyAll
class Resource1{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name) {
while(flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name = name + count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+ this.name);
flag = true;
this.notifyAll();
}
public synchronized void out() {
while(!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"...消费者..."+ this.name);
flag = false;
this.notifyAll();
}
}
使用ReentrantLock
给不同阵营配备不同的监视器,就可以避免每次都唤醒所有线程,造成不必要的性能损失
package com.tju.edu.frank;
/*
jdk1.5以后将同步和锁封装成了对象。
并将操作锁的隐式方式定义到了该对象中,
将隐式动作变成了显示动作。
Lock接口: 出现替代了同步代码块或者同步函数。将同步的隐式锁操作变成现实锁操作。
同时更为灵活。可以一个锁上加上多组监视器。
lock():获取锁。
unlock():释放锁,通常需要定义finally代码块中。
Condition接口:出现替代了Object中的wait notify notifyAll方法。
将这些监视器方法单独进行了封装,变成Condition监视器对象。
可以任意锁进行组合。(定义多个监视器监视不同对象,这就解决了notifyAll()的问题)
await();
signal();
signalAll();
*/
import java.util.concurrent.locks.*;
import java.util.concurrent.locks.ReentrantLock;
public class LockProducerConsumerDemo {
public static void main(String[] args) {
LockResource r = new LockResource();
LockProducer p = new LockProducer(r);
LockConsumer c = new LockConsumer(r);
//两个生产者两个消费者
Thread t0 = new Thread(p);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
Thread t3 = new Thread(c);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
class LockProducer implements Runnable{
private LockResource r;
LockProducer(LockResource r){
this.r = r;
}
@Override
public void run() {
while(true) {
r.set("飞机");
}
}
}
class LockConsumer implements Runnable{
private LockResource r;
LockConsumer(LockResource r){
this.r = r;
}
@Override
public void run() {
while(true) {
r.out();
}
}
}
//以前锁和监视器是一个对象,现在锁和监视器可以不同了,一个锁可以创建多个监视器监视不同对象
class LockResource{
private String name;
private int count = 1;
private boolean flag = false;
private final Lock lock = new ReentrantLock();
// private final Condition con = lock.newCondition(); 这样做给所有线程只配备一个监视器 然后signalAll(),和之前notifyAll()一样唤醒了不必要的线程
//为生产者和消费者定义不同的监视器,这样就可以做到用signal()只唤醒对方的线程,避免的性能问题
private final Condition pro_con = lock.newCondition();
private final Condition con_con = lock.newCondition();
public void set(String name) {
lock.lock();
try {
while(flag) {
try {
pro_con.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name = name + count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+ this.name);
flag = true;
con_con.signal();
} finally {
lock.unlock();
}
}
public void out() {
lock.lock();
try {
while(!flag) {
try {
con_con.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"...消费者..."+ this.name);
flag = false;
pro_con.signal();
} finally {
lock.unlock();
}
}
}
使用线程池和阻塞队列
这是最方便和简洁的方式
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
public class ProducerConsumerDemoByBlockingQueue {
public static final SynchronousQueue<String> queue = new SynchronousQueue<String>();
public static void main(String[] args) {
Resource1 r = new Resource1();
ExecutorService service = Executors.newCachedThreadPool();
//一个生产者一个消费者
for (int i = 0; i < 1; i++) {
service.execute(new Producer(r,queue));
}
for (int i = 0; i < 1; i++) {
service.execute(new Consumer(r,queue));
}
service.shutdown();
}
static class Producer implements Runnable{
private Resource1 r;
private SynchronousQueue<String> queue;
Producer(Resource1 r, SynchronousQueue<String> queue){
this.r = r;
this.queue = queue;
}
@Override
public void run() {
while(true) {
r.set("飞机");
}
}
}
static class Consumer implements Runnable{
private Resource1 r;
private SynchronousQueue<String> queue;
Consumer(Resource1 r, SynchronousQueue<String> queue){
this.r = r;
this.queue = queue;
}
@Override
public void run() {
while(true) {
r.out();
}
}
}
static class Resource1{
private String name;
private int count = 1;
public void set(String name) {
while(true) {
try {
this.name = name + count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+ this.name);
queue.put(this.name);
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void out() {
while(true) {
try {
String s = queue.take();
System.out.println(Thread.currentThread().getName()+"...消费者..."+ s);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}