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

这篇文章主要介绍了java信号量控制线程打印顺序的示例,如ABCABC这样输出线程,大家参考使用吧

复制代码 代码如下:

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     try {
     curSemp.acquire();
     System.out.println(name);
     nextSemp.release();
    } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
    }
   }
  }

 }

}

以上就是java信号量控制线程打印顺序的示例分享的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java