forked from hansiming/JavaProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaxOMatic.java
More file actions
107 lines (74 loc) · 1.79 KB
/
WaxOMatic.java
File metadata and controls
107 lines (74 loc) · 1.79 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
package com.csdhsm.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Car{
private boolean waxOn = false;
public synchronized void waxed(){
waxOn = true;//Ready to buff
notifyAll();
}
public synchronized void buffed(){
waxOn = false;//Ready for another coat of wax
notifyAll();
}
public synchronized void waitForWaxing() throws InterruptedException{
while(waxOn == false){
wait();
}
}
public synchronized void waitForBuffing() throws InterruptedException{
while(waxOn == true){
wait();
}
}
}
class WaxOn implements Runnable{
private Car car;
public WaxOn(Car c){ car = c;}
@Override
public void run() {
try {
while(!Thread.interrupted()){
System.out.print("Wax On ! ");
TimeUnit.MILLISECONDS.sleep(200);
car.waxed();
car.waitForBuffing();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Ending Wax On task");
}
}
class WaxOff implements Runnable{
private Car car;
public WaxOff(Car car) {
this.car = car;
}
@Override
public void run() {
try {
while(!Thread.interrupted()){
car.waitForWaxing();
System.out.print("WaxOff ! ");
TimeUnit.MILLISECONDS.sleep(200);
car.buffed();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("Ending Wax Off task");
}
}
public class WaxOMatic {
public static void main(String[] args) throws InterruptedException {
Car car = new Car();
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new WaxOff(car));
exec.execute(new WaxOn(car));
TimeUnit.SECONDS.sleep(5);
exec.shutdownNow();
}
}