源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

java信号量控制线程打印顺序的示例分享

  • 时间:2020-03-16 16:26 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java信号量控制线程打印顺序的示例分享
[u]复制代码[/u] 代码如下:
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();     }    }   }  } }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部