java java后台任务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2804376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:55:38  来源:igfitidea点击:

java background task

javamultithreading

提问by markovuksanovic

I was wondering which would be the most efficient approach to implement some kind of background task in java (I guess that would be some kind of nonblocking Threads). To be more precise - I have some java code and then at some point I need to execute a long running operation. What I would like to do is to execute that operation in the background so that the rest of the program can continue executing and when that task is completed just update some specific object which. This change would be then detected by other components.

我想知道哪种方法是在 java 中实现某种后台任务的最有效方法(我猜那将是某种非阻塞线程)。更准确地说 - 我有一些 java 代码,然后在某个时候我需要执行一个长时间运行的操作。我想做的是在后台执行该操作,以便程序的其余部分可以继续执行,当该任务完成时,只需更新一些特定的对象。然后其他组件会检测到此更改。

回答by Michael Mrozek

You want to make a new thread; depending on how long the method needs to be, you can make it inline:

您想创建一个新线程;根据方法需要多长时间,您可以使其内联:

// some code
new Thread(new Runnable() {
    @Override public void run() {
        // do stuff in this thread
    }
}).start();

Or just make a new class:

或者只是创建一个新类:

public class MyWorker extends Thread {
    public void run() {
        // do stuff in this thread
    }
}

// some code
new MyWorker().start();

回答by pritam potnis

Make a thread. Mark this thread as Daemon. The JVM exits when the only thread running are all daemon threads.

做一个线程。将此线程标记为守护进程。当唯一运行的线程都是守护线程时,JVM 将退出。

回答by phtrivier

Na?ve idea : you might be able to create Thread, give it a low priority, and do a loop of :

天真的想法:你可以创建线程,给它一个低优先级,然后做一个循环:

  • doing a little bit of work
  • using yield or sleep to let other threads work in parrallel
  • 做一点工作
  • 使用 yield 或 sleep 让其他线程并行工作

That would depend on what you actually want to do in your thread

这将取决于您在线程中实际想要做什么

回答by Ryan Elkins

Yes, you're going to want to spin the operation off on to it's own thread. Adding new threads can be a little dangerous if you aren't careful and aware of what that means and how resources will interact. Here is a good introduction to threadsto help you get started.

是的,您会想要将操作分拆到它自己的线程上。如果您不小心并且不了解这意味着什么以及资源将如何交互,那么添加新线程可能会有点危险。这里很好地介绍了线程,可帮助您入门。