2015-09-07 11:44:36 -06:00
|
|
|
// concurrency/SelfManaged.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.
|
2015-06-15 17:47:35 -07:00
|
|
|
// A Runnable containing its own driver Thread.
|
|
|
|
|
|
|
|
public class SelfManaged implements Runnable {
|
|
|
|
private int countDown = 5;
|
|
|
|
private Thread t = new Thread(this);
|
|
|
|
public SelfManaged() { t.start(); }
|
|
|
|
@Override
|
|
|
|
public String toString() {
|
|
|
|
return Thread.currentThread().getName() +
|
|
|
|
"(" + countDown + "), ";
|
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public void run() {
|
|
|
|
while(true) {
|
|
|
|
System.out.print(this);
|
|
|
|
if(--countDown == 0)
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
for(int i = 0; i < 5; i++)
|
|
|
|
new SelfManaged();
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
Thread-0(5), Thread-4(5), Thread-3(5), Thread-1(5),
|
|
|
|
Thread-2(5), Thread-2(4), Thread-2(3), Thread-1(4),
|
|
|
|
Thread-3(4), Thread-4(4), Thread-0(4), Thread-4(3),
|
|
|
|
Thread-3(3), Thread-1(3), Thread-2(2), Thread-1(2),
|
|
|
|
Thread-3(2), Thread-4(2), Thread-0(3), Thread-4(1),
|
|
|
|
Thread-3(1), Thread-1(1), Thread-2(1), Thread-0(2),
|
|
|
|
Thread-0(1),
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|