思路
1、定义两个信号量,A的默认个数为1,B的默认值为0,一个用于打印A,一个用于打印B
2、A线程获取到信号量A后打印"A",打印完后释放一个信号量B,让B可以打印
3、B线程获取到信号量B后打印"B",打印完后释放一个信号量A,让A可以打印
public class TestPrint {
public static void main(String[] args) {
Semaphore semaphoreA = new Semaphore(1);
Semaphore semaphoreB = new Semaphore(1);
PrintA printA = new PrintA(semaphoreA,semaphoreB);
PrintB printB = new PrintB(semaphoreA,semaphoreB);
try {
Thread tA = new Thread(printA);
Thread tB = new Thread(printB);
tA.start();
tB.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class PrintA implements Runnable{
Semaphore semaphoreA;
Semaphore semaphoreB;
public PrintA(Semaphore semaphoreA,Semaphore semaphoreB){
this.semaphoreA = semaphoreA;
this.semaphoreB = semaphoreB;
}
@Override
public void run(){
try {
for(int i = 0;i<10;i++) {
semaphoreA.acquire(1);
System.out.println("A");
semaphoreB.release(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class PrintB implements Runnable{
Semaphore semaphoreA;
Semaphore semaphoreB;
public PrintB(Semaphore semaphoreA,Semaphore semaphoreB){
this.semaphoreA = semaphoreA;
this.semaphoreB = semaphoreB;
}
@Override
public void run(){
for(int i = 0;i<10;i++) {
try {
semaphoreB.acquire(1);
System.out.println("B");
semaphoreA.release(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}