package other.thread15;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class DemoService {
private Lock lock = new ReentrantLock();
private Condition conditionA = lock.newCondition();
private Condition conditionB = lock.newCondition();
public void awaitA() {
try {
lock.lock();
System.out.println("await A 时间为:" + System.currentTimeMillis());
conditionA.await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void awaitB() {
try {
lock.lock();
System.out.println("await B 时间为:" + System.currentTimeMillis());
conditionB.await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void signalA() {
try {
lock.lock();
System.out.println("signal A 时间为:" + System.currentTimeMillis());
conditionA.signalAll();
}finally {
lock.unlock();
}
}
public void signalB() {
try {
lock.lock();
System.out.println("signal B 时间为:" + System.currentTimeMillis());
conditionB.signalAll();
}finally {
lock.unlock();
}
}
}
package other.thread15;
public class ThreadA extends Thread {
private DemoService service;
public ThreadA(DemoService service) {
this.service = service;
}
@Override
public void run() {
service.awaitA();
}
}
package other.thread15;
public class ThreadB extends Thread {
private DemoService service;
public ThreadB(DemoService service) {
this.service = service;
}
@Override
public void run() {
service.awaitB();
}
}
package other.thread15;
public class Test {
public static void main(String[] args) throws InterruptedException {
DemoService service = new DemoService();
ThreadA threadA = new ThreadA(service);
threadA.start();
ThreadB threadB = new ThreadB(service);
threadB.start();
Thread.sleep(1000);
service.signalA();
}
}