Skip to content

Instantly share code, notes, and snippets.

@zhanggang807
Created October 29, 2018 01:02
Show Gist options
  • Save zhanggang807/d55c97d882f4ac817b749a34c5f58475 to your computer and use it in GitHub Desktop.
Save zhanggang807/d55c97d882f4ac817b749a34c5f58475 to your computer and use it in GitHub Desktop.
线程会停止吗?
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