复制代码代码如下::
Import Java.util.Concurrent.Semaphor;
öffentliche Klassen -Dreiberadung {
public static void main (String [] args) löst InterruptedException {
Semaphore SEMPA = neues Semaphor (1);
Semaphore sempb = neues semaphor (0);
Semaphore SEMPC = neues Semaphor (0);
int n = 100;
Threada = new printhead (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 ();
}
Statische Klasse Printhread erweitert Thread {
int n;
Semaphor Cursemp;
Semaphore NextSemp;
Zeichenfolge Name;
public printhead (int n, semaphore cursemp, semaphore Nextsemp, String -Name) {
N = n;
this.cursemp = cursemp;
this.NextSEMP = NEXTSEMP;
this.name = name;
}
public void run () {
für (int i = 0; i <n; ++ i) {
versuchen {
cursemp.acquire ();
System.out.println (Name);
NextSemp.Release ();
} catch (InterruptedException e) {
Thread.currentThread (). Interrupt ();
}
}
}
}
}