如何将可调用线程作为守护线程?
这是我正在尝试的。我正在尝试执行一组线程,其中一个线程没有完成并进入无限循环。它所做的是,即使所有代码语句都已执行,程序的主线程也不会终止。之后主线程进入挂起模式。
这是相同的代码片段。
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中的悬空线程的问题中,我了解到我必须将我的线程作为守护线程。