import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Res {
public String userSex;
public String userName;
public boolean flag = false;
Lock lock = new ReentrantLock();
}
import java.util.concurrent.locks.Condition;
public class IntTread extends Thread{
private Res res;
Condition condition;
public IntTread(Res res, Condition condition) {
this.res = res;
this.condition = condition;
}
@Override
public void run() {
int count = 0;
while (true){
try {
res.lock.lock();
if (res.flag){
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count==0){
res.userName = "男zs";
res.userSex = "男";
}else {
res.userName = "女xh";
res.userSex = "女";
}
count = (count + 1)%2;
res.flag = true;
condition.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
res.lock.unlock();
}
}
}
}
import java.util.concurrent.locks.Condition;
public class OutThread extends Thread {
private Res res;
private Condition condition;
public OutThread(Res res, Condition condition) {
this.res = res;
this.condition = condition;
}
@Override
public void run() {
while (true){
try {
res.lock.lock();
if (!res.flag){
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(res.userName + "--" + res.userSex);
res.flag = false;
condition.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
res.lock.unlock();
}
}
}
}
import java.util.concurrent.locks.Condition;
/**
* Condition的功能类似于在传统的线程技术中的,Object.wait()和Object.notify()的功能
* condition await() signal()
*/
public class Main {
public static void main(String[] args){
Res res = new Res();
Condition condition = res.lock.newCondition();
IntTread intTread = new IntTread(res,condition);
OutThread outThread = new OutThread(res,condition);
intTread.start();
outThread.start();
}
}
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 与重入锁相关联的Condition
* 和Object.wait(),notify()方法一样,当 线程使用Condition.await()时,要求线程持有相关的重入锁,
* 在Condition.await()调用后,这个线程会释放这把锁。同理,在condition.signal()方法调用时,也要求
* 线程先获得相关的锁,在condition.signal()方法调用后,系统会从当前Condition对象的等待队列中唤醒一个线程,
* 一旦线程被唤醒,它会重新尝试获得与之绑定的重入锁,一旦成功获取,就可以继续执行了。因此,在signal()方法调用之后,
* 一般需要释放相关的锁,让给被唤醒的线程,让它继续执行。
*/
public class ConditionDemo implements Runnable{
public static ReentrantLock lock = new ReentrantLock();
public static Condition condition = lock.newCondition();
@Override
public void run() {
try {
lock.lock();
condition.await();//使当前线程等待,同时释放当前锁
System.out.println("Thread is going on");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException{
ConditionDemo t = new ConditionDemo();
Thread t1 = new Thread(t);
t1.start();
Thread.sleep(2000);
//通知线程t1继续执行
lock.lock();//调用signal()的方法时,线程要先获得相关的锁
condition.signal();//唤醒一个在等待中的线程
lock.unlock();//signal()调用后释放相关的锁给被唤醒的线程
}
}