-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path顺序打印字母A到Z.java
43 lines (36 loc) · 1.28 KB
/
顺序打印字母A到Z.java
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
package com.algorithm.demo.thread;
public class 顺序打印字母A到Z {
private volatile static char c = 'A';
private volatile static int count = 0;
public static void main(String[] args) {
method();
}
/**
* 一个多线程的问题,用三个线程,顺序打印字母A-Z,输出结果是1A 2B 3C 1D 2E...
*/
public static void method() {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (this) {
try {
int threadId = Integer.parseInt(Thread.currentThread().getName());
while (count < 26) {
if (count % 3 == threadId - 1) {
System.out.println("线程id : " + threadId + " " + (char) (c++) + " count " + count);
count++;
notifyAll();
} else {
wait();
}
}
} catch (Exception e) {
}
}
}
};
new Thread(r, "1").start();
new Thread(r, "2").start();
new Thread(r, "3").start();
}
}