复制代码代码如下:
impor java.util.concurrent.semaphore;
kelas publik threethread {
public static void main (string [] args) melempar interruptedException {
Semaphore sempa = semaphore baru (1);
Semaphore sempb = semaphore baru (0);
Semaphore sempc = semaphore baru (0);
int n = 100;
Thread threada = printThread baru (n, sempA, sempb, "a");
Thread threadB = new printThread (n, SempB, Sempc, "B");
Thread threadc = printThread baru (n, sempc, sempa, "c");
threada.start ();
threadb.start ();
threadc.start ();
}
class static printThread memperluas utas {
int n;
Cursemp semaphore;
Semaphore nextsemp;
Nama string;
Public PrintThread (int n, Semaphore Cursemp, Semaphore NextSemp, String Name) {
N = n;
this.cursemp = cursemp;
this.nextsemp = nextsemp;
this.name = name;
}
public void run () {
untuk (int i = 0; i <n; ++ i) {
mencoba {
Cursemp.acquire ();
System.out.println (nama);
nextsemp.release ();
} catch (InterruptedException e) {
Thread.currentThread (). Interrupt ();
}
}
}
}
}