forked from slgobinath/Java-Helps-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJoinDemo.java
More file actions
53 lines (49 loc) · 1.39 KB
/
JoinDemo.java
File metadata and controls
53 lines (49 loc) · 1.39 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
/**
* In this sample project, Painter is waiting for Mason.
* Until mason completes his task, the painter cannot start his job.
*
* @author L.Gobinath
*/
public class JoinDemo {
public static void main(String[] args) {
Thread mason = new Thread(new Mason());
Thread painter = new Thread(new Painter(mason));
mason.start();
painter.start();
}
}
class Mason implements Runnable {
@Override
public void run() {
System.out.println("Start building.");
for (int i = 0; i < 5; i++) {
System.out.println("Building a house...");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
System.out.println("Finish building.");
}
}
class Painter implements Runnable {
private Thread mason;
public Painter(Thread mason) {
this.mason = mason;
}
@Override
public void run() {
System.out.println("Wait for mason.");
// Join this thread after the mason thread.
try {
this.mason.join();
} catch (InterruptedException ex) {}
System.out.println("Start painting.");
for (int i = 0; i < 5; i++) {
System.out.println("Painting the house...");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
System.out.println("Finish painting.");
}
}