package com.zhang.reflection.面试.多线程打印;
import java.util.concurrent.Semaphore;
public class Semaphore实现 {
private int times;
private Semaphore semaphore1=new Semaphore(1);
private Semaphore semaphore2=new Semaphore(0);
private Semaphore semaphore3=new Semaphore(0);
public Semaphore实现(int times){
this.times=times;
}
public static void main(String[] args) {
Semaphore实现 a=new Semaphore实现(10);
new Thread(()->a.printA()).start();
new Thread(()->a.printB()).start();
new Thread(()->a.printC()).start();
}
public void printA() {
try{
print("A",semaphore1,semaphore2);
}catch(Exception e){
e.printStackTrace();
}
}
public void printB() {
try{
print("B",semaphore2,semaphore3);
}catch(Exception e){
e.printStackTrace();
}
}
public void printC() {
try{
print("C",semaphore3,semaphore1);
}catch(Exception e){
e.printStackTrace();
}
}
public void print(String name,Semaphore current,Semaphore next) throws InterruptedException {
for(int i=1;i<=times;i++){
current.acquire(1);
System.out.println(name);
next.release();
}
}
}
package test;
import java.util.concurrent.Semaphore;
public class Main{
private static Semaphore s1=new Semaphore(1);
private static Semaphore s2=new Semaphore(1);
private static Semaphore s3=new Semaphore(1);
public static void PrintABC(Semaphore cur,Semaphore next){
for(int i=1;i<=10;i++){
try{
cur.acquire();
System.out.print(Thread.currentThread().getName());
next.release();
}catch (Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try{
s2.acquire();
s3.acquire();
}catch (Exception e){
e.printStackTrace();
}
new Thread(()->PrintABC(s1,s2),"A").start();
new Thread(()->PrintABC(s2,s3),"B").start();
new Thread(()->PrintABC(s3,s1),"C").start();
}
}