复制代码代码如下:
importar java.util.concurrent.semaphore;
classe pública Threethread {
public static void main (string [] args) lança interruptedException {
Semaphore sempa = novo semáforo (1);
Semaphore sempb = novo semáforo (0);
Semaphore sempc = novo semáforo (0);
int n = 100;
Thread 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 ();
}
classe estática PrintThread estende o thread {
int n;
Semáfore Cursemp;
Semáfore NextSemp;
Nome da string;
public printthread (int n, semáforo cursemp, semáforo próximo, nome da string) {
N = n;
this.cursemp = cursemp;
this.NextSemp = NextSemp;
this.name = nome;
}
public void run () {
for (int i = 0; i <n; ++ i) {
tentar {
cursemp.acquire ();
System.out.println (nome);
NextSemp.Release ();
} catch (interruptedException e) {
Thread.currentThread (). Interrupt ();
}
}
}
}
}