国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java信號量控制線程打印順序的示例分享

2019-11-26 15:45:31
字體:
來源:轉載
供稿:網友

復制代碼 代碼如下:

import java.util.concurrent.Semaphore;

public class ThreeThread {

 public static void main(String[] args) throws InterruptedException {
  Semaphore sempA = new Semaphore(1);
  Semaphore sempB = new Semaphore(0);
  Semaphore sempC = new Semaphore(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();
 }

 static class PrintThread extends Thread{

  int N;
  Semaphore curSemp;
  Semaphore nextSemp;
  String name;

  public PrintThread(int n, Semaphore curSemp, Semaphore nextSemp, String name) {
   N = n;
   this.curSemp = curSemp;
   this.nextSemp = nextSemp;
   this.name = name;
  }

  public void run() {
   for (int i = 0; i < N; ++i) {
    try {
     curSemp.acquire();
     System.out.println(name);
     nextSemp.release();
    } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
    }
   }
  }

 }

}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 咸宁市| 吉水县| 惠来县| 青岛市| 常山县| 敖汉旗| 华安县| 措美县| 乳山市| 察雅县| 金门县| 新邵县| 亚东县| 湟中县| 保山市| 神木县| 尖扎县| 夹江县| 永仁县| 新绛县| 革吉县| 庄河市| 白河县| 霸州市| 东安县| 青神县| 鲁甸县| 邢台市| 冀州市| 天津市| 宣城市| 青岛市| 潜山县| 胶州市| 土默特右旗| 穆棱市| 宾川县| 吉安市| 吉安市| 凤凰县| 铜川市|