-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreads3.java
More file actions
108 lines (90 loc) · 1.74 KB
/
Threads3.java
File metadata and controls
108 lines (90 loc) · 1.74 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//TickTock Class
class TickTock {
private static String state;
synchronized void tick(boolean flag) {
if (!flag) {
state = "ticked";
notify();
return;
}
System.out.print("Tick ");
state = "ticked";
notify();
while (state.equals("ticked")) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized void tock(boolean flag) {
if (!flag) {
state = "tocked";
notify();
return;
}
System.out.println("Tock");
state = "tocked";
notify();
while (state.equals("tocked")) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//ExampleThread
class ExampleThread implements Runnable {
private Thread thread;
private static TickTock tt;
private int tickNumber;
ExampleThread(String s, int i) {
thread = new Thread(this, s);
tickNumber = i;
tt = new TickTock();
}
static ExampleThread factoryExample(String n, int i) {
var th = new ExampleThread(n, i);
th.thread.start();
return th;
}
public void run() {
if (tickNumber == 1) {
for (int i = 0; i < 10; i++) {
tt.tick(true);
tt.tick(false);
}
} else {
for (int i = 0; i < 10; i++) {
tt.tock(true);
tt.tock(false);
}
}
}
Thread getThread() {
return thread;
}
}
//Main Class
class Threads3 {
public static void main(String[] sth) {
threading();
}
static void threading() {
int n = 2;
var t = new ExampleThread[n];
for (int i = 0; i < n; i++) {
t[i] = ExampleThread.factoryExample("#Child " + (i+1), i+1);
}
System.out.println();
try {
for (var v : t) v.getThread().join();
} catch (InterruptedException e) {
System.out.println("Error: " + e);
}
System.out.println("\nMain method done");
}
}