如何实现真正的异步 java 线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2676687/
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-08-13 10:42:36  来源:igfitidea点击:

How does one implement a truly asynchronous java thread

javamultithreadingasynchronousrunnable

提问by Ritesh M Nayak

I have a function that needs to perfom two operations, one which finishes fast and one which takes a long time to run. I want to be able to delegate the long running operation to a thread and I dont care when the thread finishes, but the threads needs to complete. I implemented this as shown below , but, my secondoperation never gets done as the function exits after the start() call. How I can ensure that the function returns but the second operation thread finishes its execution as well and is not dependent on the parent thread ?

我有一个函数需要执行两个操作,一个完成得很快,另一个需要很长时间才能运行。我希望能够将长时间运行的操作委托给一个线程,我不在乎线程何时完成,但线程需要完成。我实现了如下所示,但是,我的第二个操作从未完成,因为函数在 start() 调用后退出。我如何确保函数返回但第二个操作线程也完成其执行并且不依赖于父线程?

public void someFunction(String data)
{
   smallOperation()
   SecondOperation a = new SecondOperation();
   Thread th = new Thread(a);
   th.Start();
}

class SecondOperation implements Runnable
{
  public void run(){
  // doSomething long running
 }
} 

采纳答案by Binil Thomas

public void someFunction(final String data) {
    shortOperation(data);
    new Thread(new Runnable() {
        public void run(){
            longOperation(data);
        }
    }).start();
}

If someFunctionis called, the JVM will run the longOperationif

如果someFunction被调用,JVM 将运行longOperationif

  1. the thread running it is not marked as a daemon(in the above code it is not)
  2. the longOperation()does not throw an exception and
  3. no calls to System.exit() is made in longOperation()
  1. 运行它的线程没有被标记为守护进程(在上面的代码中不是)
  2. longOperation()不抛出一个异常
  3. 没有调用 System.exit() longOperation()

回答by danben

The JVM will not exit before the thread terminates. This code that you posted does not even compile; perhaps the problem is in your actual code.

JVM 不会在线程终止之前退出。您发布的这段代码甚至无法编译;也许问题出在您的实际代码中。

回答by Yishai

IF your second function is not getting done it has nothing to do with your function returning. If something calls System.exit()or if your function throws an exception, then the thread will stop. Otherwise, it will run until it is complete, even if your main thread stops. That can be prevented by setting the new thread to be a daemon, but you are not doing that here.

如果您的第二个功能没有完成,则与您的功能返回无关。如果有东西调用System.exit()或者如果您的函数抛出异常,则线程将停止。否则,它会一直运行直到完成,即使你的主线程停止了。这可以通过将新线程设置为守护进程来防止,但您在这里没有这样做。

回答by Martin Wantke

You create a real asynchronous thread by creating a second thread within a temporary thread.

您可以通过在临时线程中创建第二个线程来创建一个真正的异步线程。

(new Thread(new Runnable() { public void run() {
    (new Thread(new Runnable() { public void run()
    {
        /* async thread */
    }})).start();
}})).start();

回答by shx

Solution using modernJava

使用现代Java 的解决方案

public void someFunction(String data) {
    smallOperation();
    new Thread(() -> {
        // doSomething long running
    }).start();
}

回答by Abhishek Kumar

It may be late to answer this question, but here is the working solution. Just add the runnables to ExecutorService.

回答这个问题可能为时已晚,但这是可行的解决方案。只需将可运行对象添加到 ExecutorService。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

ExecutorService executor = Executors.newFixedThreadPool(10);
        executor.execute(new Runnable() {
            @Override
            public void run() {
                //your code
            }
        });

回答by Saeed Jinat

if i get your question right , you wanna invoke someFunction(), execute the short smallOperation(), run a thread to the SecondOperationand make sure that when returned from this function , the SecondOperationis completed .

如果我问对了你的问题,你想调用someFunction(),执行短smallOperation(),运行一个线程,SecondOperation并确保当从这个函数返回时,SecondOperation完成。

if the flow i suggested is correct , u only need to add the following line :

如果我建议的流程是正确的,您只需要添加以下行:

public void someFunction(String data)
{
   smallOperation()
   SecondOperation a = new SecondOperation();
   Thread th = new Thread(a);
   th.Start();
   th.join(); //add this line to make your MainThread await for this to finish . 
}

class SecondOperation implements Runnable
{
  public void run(){
  // doSomething long running
 }
} 

take a look at this article, it states that "When we invoke the join() method on a thread, the calling thread goes into a waiting state. It remains in a waiting state until the referenced thread terminates" . which i think what you trying to accomplish

看看这篇文章,它指出“当我们在线程上调用 join() 方法时,调用线程进入等待状态。它保持等待状态直到引用的线程终止”。我认为你想要完成什么

if its not the case and you wanna be notified when the SecondOperationterminates , i suggest you use asyncTask

如果不是这种情况并且您想在SecondOperation终止时收到通知,我建议您使用asyncTask