Skip to content

Instantly share code, notes, and snippets.

@kretes
Created April 17, 2014 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kretes/11002556 to your computer and use it in GitHub Desktop.
Save kretes/11002556 to your computer and use it in GitHub Desktop.
Simple switching the flag from other thread that will stop loop in thread
import org.junit.Test;
public class ThreadTest {
private boolean flag = true;
@Test
public void testName() throws Exception {
new Thread(new Runnable() {
@Override
public void run() {
while(flag) {
System.out.println("loop" + System.currentTimeMillis());
sleep(100);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
sleep(2000);
System.out.println("cancelling " + System.currentTimeMillis());
flag = false;
}
}).start();
Thread.sleep(4000);
}
//this finishes with:
// loop1397758576907
// loop1397758577008
// loop1397758577108
// cancelling 1397758577204
// Process finished with exit code 0
private void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment