public class T {
private Semaphore semaphore = new Semaphore(1);
private Semaphore s2 =new Semaphore(0);
Thread thread =new Thread(()->{
for (int i = 0; i <100 ; i++) {
try {
semaphore.acquire();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if(i%2==1) System.out.println(Thread.currentThread().getName()+"="+i);
//释放许可证 给其他线程
s2.release();
}
});
Thread thread2 =new Thread(()->{
for (int i = 0; i <100 ; i++) {
try {
s2.acquire();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if(i%2==0) System.out.println(Thread.currentThread().getName()+"=="+i);
semaphore.release();
}
});
public static void main(String[] args) {
Semaphore semaphore =new Semaphore(1);
T t =new T();
t.thread.start();
t.thread2.start();
}
}