Created
June 12, 2012 14:47
-
-
Save mgenov/2917967 to your computer and use it in GitHub Desktop.
ThredsSample.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CountingThread extends Thread { | |
private final int maxCount; | |
private final CountingThread terminationThread; | |
private boolean stopped = false; | |
public CountingThread(int maxCount, CountingThread terminationThread) { | |
this.maxCount = maxCount; | |
this.terminationThread = terminationThread; | |
} | |
@Override | |
public void run() { | |
int counter = 0; | |
while (!stopped && counter < maxCount) { | |
try { | |
Thread.sleep(500); | |
System.out.println(getName() + ":" + counter); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
counter++; | |
} | |
if (terminationThread != null) { | |
terminationThread.requestStop(); | |
} | |
} | |
public void requestStop() { | |
stopped = true; | |
} | |
} | |
@Test | |
public void testThreadTermination() { | |
CountingThread t1 = new CountingThread(15, null); | |
CountingThread t2 = new CountingThread(5, t1); | |
t1.start(); | |
t2.start(); | |
try { | |
t1.join(); | |
t2.join(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment