复制代码代码如下:
นำเข้า java.util.concurrent.semaphore;
ชั้นเรียนสาธารณะ threethread {
โมฆะคงที่สาธารณะหลัก (String [] args) พ่น InterruptedException {
semaphore sempa = semaphore ใหม่ (1);
semaphore sempb = semaphore ใหม่ (0);
semaphore sempc = semaphore ใหม่ (0);
int n = 100;
เธรดเธรด = ใหม่ printThread (n, sempa, sempb, "a");
เธรดเธรด = ใหม่ printThread (n, sempb, sempc, "b");
Thread ThreadC = ใหม่ printThread (n, sempc, sempa, "c");
threada.start ();
Threadb.start ();
Threadc.start ();
-
PrintThread คลาสคงที่ขยายเธรด {
int n;
Semaphore Cursemp;
semaphore nextsemp;
ชื่อสตริง;
Public PrintThread (int n, semaphore cursemp, semaphore nextsemp, ชื่อสตริง) {
n = n;
this.cursemp = cursemp;
this.nextSemp = NextSemp;
this.name = ชื่อ;
-
โมฆะสาธารณะเรียกใช้ () {
สำหรับ (int i = 0; i <n; ++ i) {
พยายาม {
cursemp.acquire ();
System.out.println (ชื่อ);
nextsemp.release ();
} catch (interruptedException e) {
thread.currentthread (). interrupt ();
-
-
-
-
-