import
java.util.concurrent.*;
import
java.util.*;
public
class
TestGreenhouseScheduler {
private
volatile
boolean
light =
false
;
private
volatile
boolean
water =
false
;
private
String thermostat =
"Day"
;
public
synchronized
String getThermostat() {
return
thermostat;
}
public
synchronized
void
setThermostat(String value) {
thermostat = value;
}
ScheduledThreadPoolExecutor scheduler =
new
ScheduledThreadPoolExecutor(
10
);
public
void
schedule(Runnable event,
long
delay) {
scheduler.schedule(event, delay, TimeUnit.MILLISECONDS);
}
public
void
repeat(Runnable event,
long
initialDelay,
long
period) {
scheduler.scheduleAtFixedRate(event, initialDelay, period,
TimeUnit.MILLISECONDS);
}
class
LightOn
implements
Runnable {
int
j=
0
;
public
void
run() {
System.out.println(
"Turning on lights"
+
"执行了"
+(j++));
light =
true
;
}
}
class
LightOff
implements
Runnable {
public
void
run() {
System.out.println(
"Turning off lights"
);
light =
false
;
}
}
class
WaterOn
implements
Runnable {
public
void
run() {
System.out.println(
"Turning greenhouse water on"
);
water =
true
;
}
}
class
WaterOff
implements
Runnable {
public
void
run() {
System.out.println(
"Turning greenhouse water off"
);
water =
false
;
}
}
class
ThermostatNight
implements
Runnable {
int
j=
0
;
public
void
run() {
System.out.println(
"Thermostat to night setting"
+
"执行了"
+(j++));
setThermostat(
"Night"
);
}
}
class
ThermostatDay
implements
Runnable {
public
void
run() {
System.out.println(
"Thermostat to day setting"
);
setThermostat(
"Day"
);
}
}
class
Bell
implements
Runnable {
int
j=
0
;
public
void
run() {
System.out.println(
"Bing!"
+
"执行了"
+(j++));
}
}
class
Terminate
implements
Runnable {
public
void
run() {
System.out.println(
"Terminating"
);
scheduler.shutdownNow();
new
Thread() {
public
void
run() {
System.out.println(
"nowww"
);
}
}.start();
}
}
public
static
void
main(String[] args) {
TestGreenhouseScheduler gh =
new
TestGreenhouseScheduler();
gh.schedule(gh.
new
Terminate(),
1000
*
7
);
gh.repeat(gh.
new
Bell(),
0
,
1000
);
gh.repeat(gh.
new
ThermostatNight(),
0
,
2000
);
gh.repeat(gh.
new
LightOn(),
0
,
3000
);
}
}
---结果
7
秒之后,结束所有的线程,你看Bing执行了
7
次---
Bing!执行了
0
Thermostat to night setting执行了
0
Turning on lights执行了
0
Bing!执行了
1
Thermostat to night setting执行了
1
Bing!执行了
2
Bing!执行了
3
Turning on lights执行了
1
Bing!执行了
4
Thermostat to night setting执行了
2
Bing!执行了
5
Bing!执行了
6
Thermostat to night setting执行了
3
Turning on lights执行了
2
Terminating
Bing!执行了
7
nowww