复制代码代码如下:
import java.util.concurrent.semaphore;
classe publique Threethread {
public static void main (String [] args) lance InterruptedException {
Semaphore SEMPA = nouveau sémaphore (1);
Semaphore Sempb = nouveau sémaphore (0);
Semaphore Sempc = nouveau sémaphore (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 statique printthread étend le thread {
int n;
Semaphore cursemp;
Semaphore nexemp;
Nom de chaîne;
public printthread (int n, sémaphore cursemp, sémaphore nexemp, nom de chaîne) {
N = n;
this.cursemp = cursemp;
this.NextSemp = nextSemp;
this.name = name;
}
public void run () {
pour (int i = 0; i <n; ++ i) {
essayer {
cursemp.acquire ();
System.out.println (nom);
NextSemp.Release ();
} catch (InterruptedException e) {
Thread.currentThread (). Interrupt ();
}
}
}
}
}