如何将 Callable 线程设置为守护线程?
这就是我正在尝试的。我正在尝试执行一组线程,其中一个线程未完成并进入无限循环。它的作用是即使所有代码语句都被执行,程序的主线程也不会终止。之后主线程进入挂起模式。
这是相同的代码片段。
public class MyThread implements Callable<String> {
private int value;
public MyThread(int value) {
this.value = value;
}
@Override
public String call() throws Exception {
//Thread.currentThread().setDaemon(true);
System.out.println("Executing - " + value);
if (value == 4) {
for (; ; );
}
return value + "";
}
}
主程序
public class ExecutorMain {
public static String testing() {
ExecutorService executor = null;
List<Future<String>> result = null;
String parsedValue = null;
try {
executor = Executors.newSingleThreadExecutor();
List<MyThread> threads = new ArrayList<MyThread>();
for (int i = 1; i < 10; i++) {
MyThread obj = new MyThread(i);
threads.add(obj);
}
result = executor.invokeAll(threads, Long.valueOf("4000"), TimeUnit.MILLISECONDS);
//result = executor.invokeAll(threads);
for (Future<String> f : result) {
try {
parsedValue = f.get();
System.out.println("Return Value - " + parsedValue);
} catch (CancellationException e) {
System.out.println("Cancelled");
parsedValue = "";
f.cancel(true);
}
}
executor.shutdownNow();
} catch (Exception e) {
System.out.println("Exception while running threads");
e.printStackTrace();
} finally {
List executedThreads = executor.shutdownNow();
System.out.println(executedThreads);
for (Object o : executedThreads) {
System.out.println(o.getClass());
}
}
System.out.println("Exiting....");
//System.exit(1);
return "";
}
public static void main(String[] args) {
testing();
}
}
我从之前的问题中了解到什么Java 中的悬空线程是我必须将我的线程设置为守护线程。
如何将 Callable 线程设置为守护线程?
您需要使用新的ThreadFactory
创建守护线程。在这里查看这个答案:Java 中的执行器和守护进程
默认情况下,执行器在构建池时都会创建非守护线程。但你可以自己注入ThreadFactory
它为池创建线程。
例如:
executor = ExecutorService.newSingleThreadExecutor(new MyThreadFactory());
The ThreadFactory
实施newThread
method:
Thread newThread(Runnable r)
从我上面链接的答案中复制,您可以像这样实现它:
class MyThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
}
您在问题中提到:
//Thread.currentThread().setDaemon(true);
是的,这不起作用,因为一旦线程启动,您就无法设置守护进程标志。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)