Lock锁是JDK1.5之后推出的并发包里面的关键字(注意捕获异常,释放锁)
Lock与synchronized的区别
Lock锁可以人为的释放锁(相当于汽车中的手动挡)
synchronized当线程执行完毕或者抛出异常的话,锁自动释放(相当于汽车中的自动挡)
Condition用法
Condition的功能类似于在传统的线程技术中的Object.wait()和Object.notify()的功能
package com.cppdy; import java.util.concurrent.locks.Condition;
//JDK1.5之后出现的并发包
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; class User1 { public String username;
public String sex;
// 如果flag为false 证明变量可写不可读
// 如果flag为true 证明变量可读不可写
public boolean flag = false; public Lock lock = new ReentrantLock(); } class InputThread1 extends Thread {
private User1 user;
private Condition condition; public InputThread1(User1 user,Condition condition) {
this.user = user;
this.condition=condition;
} @Override
public void run() {
int count = 0;
while (true) {
user.lock.lock();
try {
if (user.flag) {
condition.await();
}
if (count % 2 == 0) {
user.username = "cppdy";
user.sex = "nan";
} else {
user.username = "吹泡泡的魚";
user.sex = "男";
}
count++;
// 将user标记变为可读
user.flag = true;
condition.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
user.lock.unlock();
}
}
}
} class OutThread1 extends Thread {
private User1 user;
private Condition condition; public OutThread1(User1 user,Condition condition) {
this.user = user;
this.condition=condition;
} @Override
public void run() {
while (true) {
user.lock.lock();
try {
if (!user.flag) {
condition.await();
}
System.out.println(user.username + "--" + user.sex);
// 将user标记变为可写
user.flag = false;
condition.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
user.lock.unlock();
}
}
}
} public class ThreadDemo14 { public static void main(String[] args) throws Exception {
User1 user = new User1();
Condition condition=user.lock.newCondition();
InputThread1 it = new InputThread1(user,condition);
OutThread1 ot = new OutThread1(user,condition);
it.start();
ot.start();
} }