OnJava8-Examples/tasks/Joining.java

63 lines
1.4 KiB
Java
Raw Normal View History

2016-01-25 18:05:55 -08:00
// tasks/Joining.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Understanding join()
2015-06-15 17:47:35 -07:00
class Sleeper extends Thread {
private int duration;
public Sleeper(String name, int sleepTime) {
super(name);
duration = sleepTime;
start();
}
@Override
public void run() {
try {
sleep(duration);
} catch(InterruptedException e) {
2016-01-25 18:05:55 -08:00
System.out.println(getName() +
" was interrupted. " +
2015-06-15 17:47:35 -07:00
"isInterrupted(): " + isInterrupted());
return;
}
2015-11-03 12:00:44 -08:00
System.out.println(getName() + " has awakened");
2015-06-15 17:47:35 -07:00
}
}
class Joiner extends Thread {
private Sleeper sleeper;
public Joiner(String name, Sleeper sleeper) {
super(name);
this.sleeper = sleeper;
start();
}
@Override
public void run() {
try {
sleeper.join();
} catch(InterruptedException e) {
2015-11-03 12:00:44 -08:00
System.out.println("Interrupted");
2015-06-15 17:47:35 -07:00
}
2015-11-03 12:00:44 -08:00
System.out.println(getName() + " join completed");
2015-06-15 17:47:35 -07:00
}
}
public class Joining {
public static void main(String[] args) {
Sleeper
sleepy = new Sleeper("Sleepy", 1500),
grumpy = new Sleeper("Grumpy", 1500);
Joiner
dopey = new Joiner("Dopey", sleepy),
doc = new Joiner("Doc", grumpy);
grumpy.interrupt();
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Grumpy was interrupted. isInterrupted(): false
Doc join completed
Sleepy has awakened
Dopey join completed
2015-09-07 11:44:36 -06:00
*/