以下代码可以实现两个线程(A和B)任意次数的交替执行,比如,A线程执行m次,B线程执行n次,A线程又执行m次,B线程又执行n次…如此交替循环。
首先定义一个锁类,该类的作用是充当线程之间的通信角色,并定义各个线程的执行次数,同时还包含了线程的主体执行方法,代码如下:
public class Lock {
// 线程A每次执行的次数
private int aRunTimes;
// 线程A已经执行的次数
private int aRunCount = 0;
//线程B每次执行的次数
private int bRunTimes;
// 线程B已经执行的次数
private int bRunCount = 0;
//是否A线程先执行
private boolean aFist;
public Lock(int aRunTimes, int bRunTimes, boolean aFist) {
this.aRunTimes = aRunTimes;
this.bRunTimes = bRunTimes;
this.aFist = aFist;
}
public synchronized void methodA() {
// 如果A线程先执行,并且A线程已经执行的次数小于每次需要执行的次数
if (aFist && aRunCount < aRunTimes) {
System.out.println(Thread.currentThread().getName() + " 运行次数:" + aRunCount);
aRunCount++;
} else {
notify(); //唤醒B线程
aFist = false; //修改标记
aRunCount = 0; //将线程A已经执行次数归零,下次A线程执行的时候重新计数
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void methodB() {
if (!aFist && bRunCount < bRunTimes) {
System.out.println(Thread.currentThread().getName() + "运行次数:" + bRunCount);
bRunCount++;
} else {
notify();
aFist = true;
bRunCount = 0;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
定义线程A,在run()方法种循环调用lock对象的methodA()方法
public class ThreadA implements Runnable {
private Lock lock;
public ThreadA(Lock lock){
this.lock = lock;
}
@Override
public void run() {
while(true){
lock.methodA();
}
}
}
定义线程B,在run()方法种循环调用lock对象的methodB()方法
public class ThreadB implements Runnable {
private Lock lock;
public ThreadB(Lock lock){
this.lock = lock;
}
@Override
public void run() {
while(true){
lock.methodB();
}
}
}
测试类:
public class Test {
public static void main(String[] args){
// 此处表示每次线程A执行2次,线程B执行3次,线程B先执行
Lock lock =new Lock(2,3,false);
// 通过构造方法将同一个lock对象传给线程A和线程B
Thread a = new Thread(new ThreadA(lock),"线程A");
Thread b = new Thread(new ThreadB(lock),"线程B");
a.start();
b.start();
}
}