欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-23 08:38:10
复制代码 代码如下:import java.util.concurrent.semaphore; public class threethread {  pu...

复制代码 代码如下:

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

 }

}