Created
October 29, 2018 01:02
-
-
Save zhanggang807/d55c97d882f4ac817b749a34c5f58475 to your computer and use it in GitHub Desktop.
线程会停止吗?
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 java.util.concurrent.*; | |
public class StopThread { | |
private static boolean stopRequested; | |
public static void main(String[] args) throws InterruptedException { | |
Thread backgroundThread = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
int i = 0; | |
while (!stopRequested) { | |
i++; | |
System.out.println("" + i); | |
} | |
} | |
}); | |
backgroundThread.start(); | |
TimeUnit.SECONDS.sleep(1); | |
stopRequested = true; | |
/** | |
jvm尽量保证可见性,volatile 强制保证可见性 https://mp.weixin.qq.com/s/dEBBdBb5Oxr7-O2Gb9N6ow | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment