这里采用Java1.5之后的Lock锁来实现需求
需求:第一个线程写入(input)用户,另一个线程取读取(out)用户.实现读一个,写一个操作
class Res {
public String name;
public String sex;
// flag false out线程未读取值
public boolean flag = false;
public Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
}
class InpThread extends Thread {
public Res res;
public InpThread(Res res) {
this.res = res;
}
@Override
public void run() {
int count = 0;
while (true) {
// 获取锁的资源
try {
res.lock.lock();
if (res.flag) {
try {
res.condition.await();
} catch (Exception e) {
// TODO: handle exception
}
}
if (count == 0) {
res.name = "LLL丶禾羊";
res.sex = "男";
} else {
res.name = "小红";
res.sex = "女";
}
// 实现奇数和偶数
count = (count + 1) % 2;
res.flag = true;
res.condition.signal();
} catch (Exception e) {
// TODO: handle exception
} finally {
// 释放锁
res.lock.unlock();
}
}
}
}
class OutThread extends Thread {
public Res res;
public OutThread(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
try {
res.lock.lock();
if (!res.flag)
{
res.condition.await();
}
System.out.println(res.name + "---" + res.sex);
res.flag = false;
res.condition.signal();
} catch (Exception e) {
// TODO: handle exception
} finally {
res.lock.unlock();
}
}
}
}
public class ThreadDemo01 {
public static void main(String[] args) {
Res res = new Res();
InpThread inpThread = new InpThread(res);
OutThread outThread = new OutThread(res);
inpThread.start();
outThread.start();
}
}
其实上Lock的lock和unlock方法就和synchronized+wait(notify)是一样的效果,但是Lock实现了可以人为解锁。
Condition的await方法等同于wait,signal就等同于notify
需要注意的是释放锁的时候尽量在finally中取释放,这样避免了在代码中出现异常导致锁不能释放的情况(死锁)