package com.xiaozhi.procon2;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* 多生产者多消费者
* lock代替sychronized
* condition里面的await和signal代替Object的wait和notify
* condition可以区分本方线程和对方线程
*/
public class Test {
public static void main(String[] args) {
Resource resource=new Resource();
Producer producer1=new Producer(resource);
Producer producer2=new Producer(resource);
Consumer consumer1=new Consumer(resource);
Consumer consumer2=new Consumer(resource);
Thread thread1=new Thread(producer1);
Thread thread2=new Thread(producer2);
Thread thread3=new Thread(consumer1);
Thread thread4=new Thread(consumer2);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
class Resource{
private int num;
private boolean flag=false;
private Lock lock=new ReentrantLock();
private Condition condition_pro=lock.newCondition();
private Condition condition_con=lock.newCondition();
public void input()
{
lock.lock();
try {
while(flag)
condition_pro.await();
num++;
System.out.println("商品生产-----------------"+num);
flag=true;
condition_con.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void output()
{
lock.lock();
try {
while(!flag)
condition_con.await();
System.out.println("商品消费--------------------------"+num);
flag=false;
condition_pro.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
class Producer implements Runnable{
private Resource resource;
public Producer(Resource resource) {
super();
this.resource = resource;
}
@Override
public void run() {
while(true)
resource.input();
}
}
class Consumer implements Runnable{
private Resource resource;
public Consumer(Resource resource) {
super();
this.resource = resource;
}
@Override
public void run() {
while(true)
resource.output();
}
}
【重点】JDK5新特性lock和condition(多生产者多消费者:可以用来区分本方线程和对方线程)
最新推荐文章于 2023-03-30 19:28:57 发布