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

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

猜你喜欢

转载自robert-wei.iteye.com/blog/2341713