Newer
Older
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
// PDF: https://moodle.epfl.ch/pluginfile.php/3175938/mod_folder/content/0/week01-3-Introduction-to-Threads-2-with-Demo.pdf
// Video: https://mediaspace.epfl.ch/playlist/dedicated/31866/0_c46icdbx/0_zx4gncsb
// Slides: 4
package lecture1;
/** An example Thread implementation in Java. */
class ExampleThread extends Thread {
int sleepiness;
public void run() {
int i = 0;
while (i < 8) {
System.out.println(getName() + " has counter " + i);
i++;
try {
sleep(sleepiness);
} catch (InterruptedException e) {
System.out.println("Thread was interrupted.");
}
}
}
// Run from the SBT shell with `runMain lecture1.ExampleThread`.
public static void main(String[] args) {
ExampleThread t1 = new ExampleThread();
t1.sleepiness = 2;
ExampleThread t2 = new ExampleThread();
t2.sleepiness = 3;
System.out.println("Little threads did not start yet!");
t1.start();
t2.start();
System.out.println("Parent thread running!");
try {
sleep(29);
} catch (InterruptedException e) {
System.out.println("Parent thread was interrupted.");
}
System.out.println("Parent thread running!");
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println("A thread was interrupted!");
}
System.out.println("Done executing thread.");
}
}