Created
April 17, 2014 18:17
-
-
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
This file contains 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
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