package leecode;
import java.util.concurrent.Semaphore;
public class PrintAB {
static Semaphore a= new Semaphore(1);
static Semaphore b= new Semaphore(0);
static class A implements Runnable{
@Override
public void run() {
for(int i =0;i<=4;i++){
try {
a.acquire();
System.out.println("A");
b.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class B implements Runnable{
@Override
public void run() {
for(int i =0;i<=4;i++){
try {
b.acquire();
System.out.println("B");
a.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new A());
Thread t2 = new Thread(new B());
t1.start();
t2.start();
}
}
标签: