英文:
How to run Executors newSingleThreadExecutor independent of main Thread
问题
我需要独立于主线程执行一段代码,我已经通过以下方式实现了这一点:
new Thread(() -> {
someBigWork();
}).start();
这个方法可以正常工作,但我想通过Executors.newSingleThreadExecutor
来实现这个目标。
我尝试了以下代码:
public static void main() {
try {
// 一些我的代码应该在主线程中运行
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> someBigWork());
// 一些我的代码应该在主线程中运行
} catch (Exception e) {
// 一些处理代码
} finally {
executorService.shutdown();
}
}
我发现主线程只有在someBigWork()
执行完成后才退出。我通过命令行运行这段代码,我添加了一些日志,在打印日志之后程序才退出(我认为,主线程是否在等待someBigWork()
完成)。我想要独立运行someBigWork()
。我是不是漏掉了什么?如果我错了,请纠正我。
英文:
I need to execute a piece of code independently of main thread, i have achieved this through
new Thread(()->{
someBigWork()
}).start();
This works fine, but i want to achieve this via Executors newSingleThreadExecutor
I have tried the following code
public static void main()
{
try{
// some my code should run in main Thread
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> someBigWork());
// some my code should run in main Thread
}catch(Expection e){
// some handeling code
}finally{
executorService.shutdown();
}
What i see is main thread exited only after someBigWork() execution completes.
I am running this code via cmd line, i have added some logs , after pring logs the program is exited (i am think , whether main Thread is waiting for someBigWork() to complete)
I want to run someBigWork() independently.
Am i missing something ?
Please correct me if im wrong
答案1
得分: 1
以下是您要翻译的内容:
在您的代码中,主线程在执行完 someBigWork() 后偶然退出。如果您在 someBigWork() 中添加 Thread.sleep(delayInMilliseconds) 并在 main() 和 someBigWork() 的末尾记录线程名称,然后您会看到它们独立运行。
System.out.println(Thread.currentThread().getName() + ": myMethodName() 结束");
英文:
The main thread in your code exits after someBigWork() just by chance. If you add Thread.sleep(delayInMilliseconds) into someBigWork() and logging with thread's name at the end of both main() and someBigWork()
System.out.println(Thread.currentThread().getName() + ": end of myMethodName()");
then you'll see that they run independently.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论