Lock锁和Synchronized同步锁有什么本质区别,什么时候必须得用Lock锁,另外我下面的程序虽然能正常运行
,但是唤醒con.signalAll()依旧会唤醒本方线程,效率还是很低,有没有高效的方法,以前学过的但又忘了。
import java.util.concurrent.locks.*;
class Resource
{
private String name;
private int count;
private boolean flag;
//创建一个锁对象。
private Lock lock = new ReentrantLock();
private Condition con = lock.newCondition();
public void set(String name)
{
lock.lock();
try
{
while(flag)
try{con.await();}catch(Exception e){}//让生产者等待。
this.name = name+"-----"+count;
count++;
System.out.println(Thread.currentThread().getName()+".....生产者....."+this.name);
flag = true;
con.signalAll();//让生产者线程去唤醒消费者监视器上的线程。
}
finally
{
lock.unlock();
}
}
public void out()
{
lock.lock();
try
{
while(!flag)
try{con.await();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"...........消费者......"+this.name);
flag = false;
con.signalAll();
}
finally
{
lock.unlock();
}
}
}
class Producter implements Runnable
{
private Resource r;
Producter(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.set("产品");
}
}
}
class Customer implements Runnable
{
private Resource r;
Customer(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class Demo8
{
public static void main(String[] args)
{
Resource r = new Resource();
new Thread(new Producter(r)).start();
new Thread(new Customer(r)).start();
}
}
|