package Thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 多线程,生产者与消费者
* JDK5.0版本新特性
* 将同步synchronized替换成显示Lock操作
* 将Object中wait、notify、notifyAll替换了Condition对象,该对象可以用Lock锁进行获取。
* @author Again
*
*/
class ProductCustomerDemo2 {
public static void main(String[] args) {
Resource r=new Resource();
Product p=new Product(r);
Customer c=new Customer(r);
Thread t1=new Thread(p);
Thread t2=new Thread(p);
Thread t3=new Thread(c);
Thread t4=new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource2{
private String name;
private int count=1;
private boolean flag=false;
private Lock lock=new ReentrantLock();//创建锁
private Condition condition_pro=lock.newCondition();
private Condition condition_cus=lock.newCondition();
/*
* 生产者
*/
public void set(String name){
lock.lock();
while(flag){
try {
condition_pro.await();
this.name=name+"....."+count++;
System.out.println(Thread.currentThread().getName()+"----生产者----"+this.name);
flag=true;
condition_cus.signal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
/*
* 消费者
*/
public void out(){
while(!flag){
try {
condition_cus.await();
System.out.println(Thread.currentThread().getName()+"---------消费者---------"+this.name);
flag=false;
condition_pro.signal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
}
class Product2 implements Runnable{
private Resource2 r;
public Product2(Resource2 r){
this.r=r;
}
public void run() {
while(true){
r.set("商品");
}
}
}
class Customer2 implements Runnable{
private Resource2 r;
public Customer2(Resource2 r){
this.r=r;
}
public void run() {
while(true){
r.out();
}
}
}
多线程生产者与消费者JDK5.0版本新特性
最新推荐文章于 2022-10-12 13:20:00 发布