zoukankan      html  css  js  c++  java
  • JAVA 多线程轮流打印ABC

    采用Thread+Semaphore实现,思路很简单

     1 import java.io.IOException;
     2 import java.util.concurrent.Semaphore;
     3 
     4 public class PrintABC {
     5     public static int MAX_TIME = 10;
     6 
     7     public static class PrintThread extends Thread {
     8         private String printChar;
     9         private Semaphore curSemaphore, nextSemaphore;
    10 
    11         public PrintThread(String printChar, Semaphore curSemaphore,
    12                 Semaphore nextSemaphore) {
    13             this.printChar = printChar;
    14             this.curSemaphore = curSemaphore;
    15             this.nextSemaphore = nextSemaphore;
    16         }
    17 
    18         public void run() {
    19             for (int i = 0; i < MAX_TIME; ++i) {
    20                 try {
    21                     curSemaphore.acquire();  /* 请求打印需要的信号量,资源数-1,即down操作  */
    22                     System.out.println(printChar);
    23                     nextSemaphore.release(); /* 释放下一个线程打印需要的信号量,资源数+1,即up操作  */
    24                 } catch (InterruptedException e) {
    25                     // TODO Auto-generated catch block
    26                     e.printStackTrace();
    27                 }
    28 
    29             }
    30         }
    31     }
    32 
    33     public static void main(String[] args) throws IOException {
    34         Semaphore semaphoreA = new Semaphore(1); /* 只有A信号量的初始资源数为1,保证从A开始打印  */
    35         Semaphore semaphoreB = new Semaphore(0);
    36         Semaphore semaphoreC = new Semaphore(0);
    37 
    38         new PrintThread("A", semaphoreA, semaphoreB).start();
    39         new PrintThread("B", semaphoreB, semaphoreC).start();
    40         new PrintThread("C", semaphoreC, semaphoreA).start();
    41     }
    42 }
  • 相关阅读:
    moss文档库操作的几个类
    Infopath web浏览中的多项选择功能
    国际软件项目经理的七大素质转
    InfoPath中的Rich Text Box中如何加“回车”
    设计模式——策略模式
    设计模式——状态模式
    设计模式——备忘模式
    设计模式——中介者模式
    关与BaseDataList类型绑定ArrayList
    设计模式——命令模式
  • 原文地址:https://www.cnblogs.com/xiaominghupan/p/4232037.html
Copyright © 2011-2022 走看看