首页 > 技术文章 > JAVA 多线程轮流打印ABC

xiaominghupan 2015-01-18 18:14 原文

采用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 }

 

推荐阅读