多线程顺序输出字符

题目:有多个线程,要求按顺序输出a-z,结果为

1
2
3
4
5
6
7
8
[Thread-1] print [A]
[Thread-2] print [B]
[Thread-3] print [C]
[Thread-1] print [D]
[Thread-2] print [E]
[Thread-3] print [F]
[Thread-1] print [G]

实现代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;

/**
 * 多线程顺序输出字符队列
 *
 * @author heshuai
 * @version 16/1/20.
 */
public final class DataProcessor {

    private static final int THREAD_COUNT = 3;

    private static final Queue<Character> CHARACTER_QUEUE = new ArrayBlockingQueue<>('Z' - 'A' + 1);

    static {
        for (char c = 'A'; c <= 'Z'; c++) {
            CHARACTER_QUEUE.add(c);
        }
    }

    static class Worker extends Thread {

        private Semaphore curSemaphore;
        private Semaphore nextSemaphore;

        public Worker(int index, Semaphore curSemaphore, Semaphore nextSemaphore) {
            this.setName("Thread-" + index);
            this.curSemaphore = curSemaphore;
            this.nextSemaphore = nextSemaphore;
        }

        @Override
        public void run() {
            while (!CHARACTER_QUEUE.isEmpty()) {
                try {
                    curSemaphore.acquire();
                    Character character = CHARACTER_QUEUE.poll();
                    if (character == null) {
                        break;
                    }
                    System.out.println("[" + this.getName() + "] print [" + character + "]");
                } catch (Exception e) {
                    //ignore
                } finally {
                    nextSemaphore.release();
                }
            }
        }
    }

    public static void main(String[] args) {
        Semaphore[] semaphores = new Semaphore[THREAD_COUNT];
        for (int i = 0; i < THREAD_COUNT; i++) {
            semaphores[i] = new Semaphore(1);
        }

        for (int i = 1; i <= THREAD_COUNT; i++) {
            //先确保Thread-1执行
            if (i > 1) {
                try {
                    semaphores[i - 1].acquire();
                } catch (Exception e) {
                    //ignore
                }
            }
            if (i < THREAD_COUNT) {
                new Worker(i, semaphores[i - 1], semaphores[i]).start();
            } else {
                new Worker(i, semaphores[i - 1], semaphores[0]).start();
            }
        }
    }
}