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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-19 我要评论
想了解java信号量控制线程打印顺序的示例讲解的相关内容吗,在本文为您仔细讲解java信号量控制线程的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java信号量,下面大家一起来学习吧。

复制代码 代码如下:

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();
    }
   }
  }

 }

}

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们