che*_*koo 6 java multithreading
我的问题有点复杂.让我试着彻底解释一下,但是如果你需要更多的细节,请随时问我,我会添加它们.
我最近(通过实验)了解到,如果一个线程持续工作,就像一个while(true)循环中的整数运算,中断线程对它没有影响.线程继续没有发生任何事情.
现在,使用shutDown()或shutDownNow()方法杀死ThreadPoolExecutors.我检查了这些方法的代码,他们使用interrupt()调用来杀死一个线程.所以,如果所有线程都在忙着做什么,那么执行者怎么会被杀?它是如何被杀死的,例如当我们在spring应用程序中使用它时.
一个这样的执行者看起来像:
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String[] a) {
ExecutorService ex = Executors.newFixedThreadPool(50);
for (int i = 0; i < 50; i++) {
ex.execute(new Thread() {
public void run() {
try {
File f = File.createTempFile("testfile", "txt");
while (true) {
f.canRead();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
});
}
ex.shutdown();
ex.shutdownNow();
}
}
Run Code Online (Sandbox Code Playgroud)
要回答你的主要问题,除非明确告知JVM退出,否则不会System.exit().
对于应该可中断的长时间运行操作,实现的责任是通过检查中断标志Thread.currentThread().isInterrupted().
例如:
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String[] a) {
ExecutorService ex = Executors.newFixedThreadPool(50);
for (int i = 0; i < 50; i++) {
ex.execute(new Runnable() {
public void run() {
try {
File f = File.createTempFile("testfile", "txt");
while (!Thread.currentThread().isInterrupted()) {
f.canRead();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
});
}
ex.shutdown();
ex.shutdownNow();
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,创建一个Thread仅供用作实例的实例是不合适的Runnable.这样做会产生一种间接性,可能会让更多天真的程序员感到困惑.