功能
模拟线程A的A方法调用线程B的B方法,线程B的B方法调用线程A的A方法
package CSNOTES;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.lang.Thread.*;
import static java.lang.Thread.interrupted;
//A线程中的A方法 调度B线程的B方法,B线程的B方法,调度A线程中的A方法
public class ThreadDispatch {
private int number=1; //number为0A执行, number为O B执行
private Lock lock=new ReentrantLock();
private Condition condition1=lock.newCondition();
private Condition condition2=lock.newCondition();
public void A(){
lock.lock();
try {
//1.判断
while (number!=1){
condition1.await();
}
//2.干活
System.out.println(Thread.currentThread().getName()+" "+"正在干活");
//3,通知
number=0;
condition2.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void B(){
lock.lock();
try {
//1.判断
while (number!=0){
condition2.await();
}
//2.干活
System.out.println(Thread.currentThread().getName()+" "+"正在干活");
//3.通知
number=1;
condition1.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
//启动两个线程
public static void main(String[] args) {
ThreadDispatch threadDispatch=new ThreadDispatch();
Thread t1= new Thread(()->{
while (!interrupted())
threadDispatch.A();
},"A");
t1.start();
Thread t2=new Thread(()->{
while (!interrupted())
threadDispatch.B();
},"B");
t2.start();
try {
Thread.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
}
t1.interrupt();
t2.interrupt();
}
}