主要相同点:Lock能完成synchronized所实现的所有功能,同时 lock性能上高于synchronized
主要不同点:Lock有比synchronized更精确的线程语义和更好的性能。synchronized会自动释放锁,而Lock一定要求程序员手工释放,并且必须在finally从句中释放。
另外,Synchronized---对象加锁,Lock---基于栈中的框架,而不是具体的某个对象,只需要在栈里设置锁的开始和结束就行,不用关心大小对象的变化...、
主要不同点:Lock有比synchronized更精确的线程语义和更好的性能。synchronized会自动释放锁,而Lock一定要求程序员手工释放,并且必须在finally从句中释放。
另外,Synchronized---对象加锁,Lock---基于栈中的框架,而不是具体的某个对象,只需要在栈里设置锁的开始和结束就行,不用关心大小对象的变化...、
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TestThread{
private final static Lock lock = new ReentrantLock();
private final static Condition produced = lock.newCondition();
private final Condition consumed = lock.newCondition();
boolean available = false;
static int k=100;
public static void main(String[] args){
/*lock.lock();
try{
for(int i=3;i>0;i--){
System.out.println("------"+i+"-----");
produced.await(3,TimeUnit.SECONDS);
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}*/
final TestThread t = new TestThread();
Thread proTh = new Thread(){
public void run(){
try {
t.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread cusTh = new Thread(){
public void run(){
try {
t.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
ExecutorService service = Executors.newCachedThreadPool();
service.submit(cusTh);
for(int i=3;i>0;i--){
service.submit(proTh);
}
service.shutdown();
}
/**
* 生产者
* @throws InterruptedException
*/
public void produce() throws InterruptedException {
lock.lock();
try {
/*if(available){
// produced.await(); //放弃lock进入睡眠
System.out.println("-------------");
consumed.signal();
produced.await();
}*/
System.out.println("-----start------");
//consumed.signal();
// produced.await(10,TimeUnit.SECONDS);
Thread.sleep(1000);
//consumed.signal(); //发信号唤醒等待这个condition的线程
/*生产苹果*/
System.out.println("apple produced.");
available = true;
System.out.println("produce----->k="+k);
k--;
} finally {
lock.unlock();
}
}
/**
* 消费者
* @throws InterruptedException
*/
public synchronized void consume() throws InterruptedException {
//lock.lock();
// try {
/* if(!available){
System.out.println("1111111111");
produced.signal();
consumed.await();//放弃lock进入睡眠
//Thread.sleep(1000);
}*/
// consumed.await(5,TimeUnit.SECONDS);
Thread.sleep(5000);
/*吃苹果*/
System.out.println("apple consumed.");
available = false;
//produced.signal();//发信号唤醒等待这个condition的线程
System.out.println("consume----->k="+k);
k--;
/* } finally {
lock.unlock();
}*/
}
}