我是线程新手,所以如果请给我一个关于我案例的建议。
我想创建一个新线程来做某事我不关心这个线程是否可以完成。
我打算使用ExecutorCompletionService来完成我的工作,但这个课程不适合我。它必须调用take或poll来排空队列以避免内存泄漏。所以,这意味着我必须等到线程完成。我从这个question
中读到了这个这是当前的代码
ExecutorService executor = Executors.newCachedThreadPool();
CompletionService<Entity> completion = new ExecutorCompletionService<>(executor);
DoSomeThingClass doSomething = getInstance();
completion.submit(doSomething);
executor.shutdown();
// Continue to do other job and I don't care whenever doSomeThing is complete.
// However when doSomeThing finish, I don't need to do anything to avoid memory leak
出于这个原因,请举例说明我的案例和一些框架代码。
非常感谢
答案 0 :(得分:2)
您可以将此主题标记为“守护程序”。当您的主线程完成后,您的应用就会退出。
public static void main(String[] args)
{
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
} catch(InterruptedException e) {}
System.out.println("Thread 2 is finished");
}
});
t.setDaemon(true);
t.start();
System.out.println("Thread 1 is finished");
}
答案 1 :(得分:1)
您可以使用Spring TaskExecutor,提升线程来运行任务非常有用。
import org.springframework.core.task.TaskExecutor;
public class TaskExecutorExample {
private class MessagePrinterTask implements Runnable {
private String message;
public MessagePrinterTask(String message) {
this.message = message;
}
public void run() {
System.out.println(message);
}
}
private TaskExecutor taskExecutor;
public TaskExecutorExample(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void printMessages() {
for(int i = 0; i < 25; i++) {
taskExecutor.execute(new MessagePrinterTask("Message" + i));
}
}
}
您可以在此处查看Spring Task Execution文档:
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html
答案 2 :(得分:0)
与您一起编写未来概念
Future ft=completion.submit(doSomething);
ft.get(timeOut, TimeUnit.MILLISECONDS);
在这里你可以指定执行线程的时间,如果它无法获得执行线程get kill(不是100%肯定)意味着它试图中断线程并试图杀死
答案 3 :(得分:0)
我可以通过以下代码解决我的问题
public static void main(
String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
} finally {
System.out.println("Thread 2 is finished");
}
}
});
executor.shutdown();
System.out.println("Thread 1 is finished");
}