複製代碼代碼如下:
導入java.util.concurrent.semaphore;
公共類三項{
公共靜態void main(string [] args)拋出InterruptedException {
信號sempa =新信號(1);
信號sempb =新信號(0);
信號sempc =新信號(0);
int n = 100;
線程threada = new printThread(n,sempa,sempb,“ a”);
thread threadB = new printThread(n,sempb,sempc,“ b”);
thread threadC = new printThread(n,sempc,sempa,“ c”);
threada.start();
threadB.start();
threadc.start();
}
靜態類PrintThread擴展了線程{
int n;
信號函數cursemp;
信號sextsemp;
字符串名稱;
public printThread(int n,信號函數cursemp,信號semaphore sempsemp,字符串名稱){
n = n;
this.cursemp = cursemp;
this.nextSemp = nextSemp;
this.name = name;
}
public void run(){
for(int i = 0; i <n; ++ i){
嘗試 {
cursemp.Acquire();
system.out.println(name);
NextSemp.Release();
} catch(InterruptedException e){
thread.currentThread()。interrupt();
}
}
}
}
}