import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 1.5中
* 将synchronize 替换成 lock(lock中是锁多个对象而非synchronize锁单一对象)
* wait,signal,singalALL 被Condition替换
*
*/
class Resource{
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_con = lock.newCondition();
public void set(String name) throws InterruptedException{
lock.lock();
try{
while (flag)
condition_pro.await();
this.name = name + "--" + count++;
System.out.println(Thread.currentThread().getName()+"...product..."+this.name);
flag = true;
condition_con.signalAll();
}
finally{
lock.unlock();
}
}
public void out() throws InterruptedException {
lock.lock();
try{
while(!flag)
this.condition_con.await();
System.out.println(Thread.currentThread().getName()+"...consumer..."+this.name);
flag = false;
condition_pro.signalAll();
}finally{
lock.unlock();
}
}
}
class Consumer implements Runnable{
private Resource resource;
public Consumer(Resource resource) {
// TODO Auto-generated constructor stub
this.resource = resource;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
resource.out();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Product implements Runnable{
private Resource resource;
public Product(Resource resource) {
// TODO Auto-generated constructor stub
this.resource = resource;
}
public void run() {
// TODO Auto-generated method stub
while(true){
try {
resource.set("QQ");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Hello {
public static void main(String[] args) {
Resource resource = new Resource();
Consumer consumer1 = new Consumer(resource);
Consumer consumer2 = new Consumer(resource);
Product product1 = new Product(resource);
Product product2 = new Product(resource);
Thread t1 = new Thread(consumer1);
Thread t2 = new Thread(consumer2);
Thread t3 = new Thread(product1);
Thread t4 = new Thread(product2);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Java JDK1.5 Condition方法
最新推荐文章于 2022-04-29 11:13:59 发布