`

使用Semaphore优雅解决打印ABC, ABCD 的问题

    博客分类:
  • JAVA
阅读更多
public class ABCPrint {
  public static void main(String[] args){
    Semaphore sa = new Semaphore(1);
    Semaphore sb = new Semaphore(0);
    Semaphore sc = new Semaphore(0);
    int count = 10;

    ExecutorService service = Executors.newFixedThreadPool(3);
    service.execute(new PrintTask("A", sa, sb, count));
    service.execute(new PrintTask("B", sb, sc, count));
    service.execute(new PrintTask("C\n", sc, sa, count));
    service.shutdown();
  }

  static class PrintTask implements Runnable{
    private String str;

    private Semaphore curr;

    private Semaphore next;

    private int count;

    public PrintTask(String str, Semaphore curr, Semaphore next, int count){
      this.str = str;
      this.curr = curr;
      this.next = next;
      this.count = count;
    }

    @Override
    public void run() {
      while(true){
        if(count > 0){
          try {
            curr.acquire();
            System.out.print(str);
            next.release();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          count --;
        }else{
          break;
        }
      }
    }
  }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics