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

时间:2023-05-09 12:27:38 


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

 }

}

标签:java信号量
0
投稿

猜你喜欢

  • Java基于Swing实现的打猎射击游戏代码

    2021-06-29 17:04:56
  • kafka消费者kafka-console-consumer接收不到数据的解决

    2022-04-26 06:05:42
  • 如何让java只根据数据库表名自动生成实体类

    2022-02-24 04:25:52
  • 实例化JFileChooser对象报空指针异常问题的解决办法

    2023-10-05 11:36:18
  • Java中用爬虫进行解析的实例方法

    2021-06-23 09:07:00
  • Spring spel表达式使用方法示例

    2023-08-25 00:43:32
  • IntelliJ IDEA2019实现Web项目创建示例

    2023-06-05 00:29:33
  • android效果TapBarMenu绘制底部导航栏的使用方式示例

    2023-07-29 20:53:36
  • 从零开始学springboot整合feign跨服务调用的方法

    2023-05-15 18:30:22
  • 利用logback filter过滤某个类 屏蔽某个类

    2023-07-25 20:38:08
  • java8 stream 如何打印数据元素

    2022-08-20 18:40:02
  • 详解Spring boot上配置与使用mybatis plus

    2023-02-27 08:53:11
  • 解决微服务中关于用户token处理到的坑

    2022-05-21 08:31:03
  • java自定义注解实现前后台参数校验的实例

    2023-04-27 23:53:21
  • Android保存联系人到通讯录的方法

    2023-01-28 16:44:40
  • mybatis使用collection嵌套查询的实现

    2021-07-06 22:04:58
  • c# BackgroundWorker使用方法

    2021-05-27 00:49:12
  • C#实现程序开机启动的方法

    2023-09-23 00:55:20
  • Android网络工具类NetworkUtils详解

    2022-12-08 05:18:43
  • java之swing下拉菜单实现方法

    2023-07-12 04:55:30
  • asp之家 软件编程 m.aspxhome.com