/
004_Scheduler.java
54 lines (43 loc) · 1.37 KB
/
004_Scheduler.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
44
45
46
47
48
49
50
51
52
53
// Coding Interviews: Questions, Analysis & Solutions
// Harry He
public class Scheduler {
public class SimpleThread extends Thread{
private int value;
public SimpleThread(int num) {
this.value = num;
start();
}
public void run(){
while(true) {
synchronized(this){
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.print(value + " ");
}
}
}
}
static final int COUNT = 3;
static final int SLEEP = 37;
public static void main(String args[]) {
Scheduler scheduler = new Scheduler();
SimpleThread threads[] = new SimpleThread[COUNT];
for(int i = 0; i < COUNT; ++i)
threads[i] = scheduler.new SimpleThread(i + 1);
int index = 0;
while(true){
synchronized(threads[index]) {
threads[index].notify();
}
try {
Thread.sleep(SLEEP);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
index = (++index) % COUNT;
}
}
}