一、锁与监视器
1、Lock
用面向对象的思想,用Lock对象显性锁替换了原来的synchronized的隐性锁。
代码示例:
Lock l = new ReentrantLock();
l.lock(); //获得锁
try {
// 需要同步的代码
} finally {
l.unlock(); //必须释放锁
}
2、Condition
里面有三个方法:await()、singal()、singalAll();相对于object中的唤醒方法。但是,这些方法是和Lock对象通过其方法newCondition绑定在一起的。
Condition con = l. newCondition(); (l是Lock的对象)
con. await(); con. singal(); con. singalAll();
3、锁的对比
二、代码实例(参考代码:ThreadCom4.java)
该代码只是将多生产多消费的代码采用新特性编写的。
import java.util.concurrent.locks.*;
class Resource4 {
private String name;
private int count = 0;
private boolean flag = false;
private void setName(String name) {
this.name = name;
count++;
}
//创建一个锁的对象
Lock l = new ReentrantLock();
//通过已有的锁获取监视器,一组是监视生产者,一组监视消费者。
Condition pro_con = l.newCondition();
Condition con_con = l.newCondition();
public void producer() {
l.lock();
try {
while (flag) {
try {
pro_con.await();
} catch (InterruptedException e) {
}
}
setName("包子");
System.out.println(Thread.currentThread().getName() + name + "...生产者..." + count);
con_con.signal(); //唤醒消费线程
flag = true;
} finally {
l.unlock(); //必须释放锁
}
}
public synchronized void consumer() {
//if(!flag) //没有馒头就等待
l.lock(); //打开锁
try {
while (!flag) {
try {
con_con.await();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + name + "...消费者..." + count);
pro_con.signal();//唤醒生产线程
flag = false;
} finally {
l.unlock(); //释放锁
}
}
}
class ThreadPro implements Runnable {
private Resource4 r;
ThreadPro(Resource4 r) {
this.r = r;
}
public void run() {
while (true) {
r.producer();
}
}
}
class ThreadCon implements Runnable {
private Resource4 r;
ThreadCon(Resource4 r) {
this.r = r;
}
public void run() {
while (true) {
r.consumer();
}
}
}
public class ThreadCom4 {
public static void main(String[] args) {
Resource4 r = new Resource4();
ThreadPro p = new ThreadPro(r);
ThreadCon c = new ThreadCon(r);
Thread t0 = new Thread(p);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
Thread t3 = new Thread(c);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
输出结果:
。
。
Thread-2包子...消费者...28756
Thread-0包子...生产者...28757
Thread-3包子...消费者...28757
Thread-1包子...生产者...28758
Thread-3包子...消费者...28758
Thread-0包子...生产者...28759
Thread-3包子...消费者...28759
Thread-1包子...生产者...28760
Thread-3包子...消费者...28760
Thread-0包子...生产者...28761
。
。