20

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 ?

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
 }
} 
4

7 回答 7

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

ifsomeFunction被调用,JVM 将运行longOperationif

  1. 运行它的线程未标记为守护进程(在上面的代码中不是)
  2. longOperation()不会抛出异常并且
  3. 没有调用 System.exit()longOperation()
于 2010-04-20T16:58:13.620 回答
1

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.

于 2010-04-20T16:11:10.347 回答
1

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.

于 2010-04-20T16:11:22.790 回答
1

回答这个问题可能为时已晚,但这是可行的解决方案。只需将可运行文件添加到 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
            }
        });
于 2019-04-19T07:11:17.563 回答
1

从 Java 1.8 开始,您可以非常简单地运行异步代码。下一个代码见:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore;

public class HelloWorld {
  public static void main(String[] args) {
    CompletableFuture<String> future = CompletableFuture.supplyAsync(()->
      //run the code async        
      "result"
    );
    String result = future.join(); //wait async result
    System.out.println(result);
  }
}
于 2021-02-03T14:55:44.557 回答
0

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

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

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
 }
} 

看一下这篇文章,它指出“当我们在线程上调用 join() 方法时,调用线程进入等待状态。它一直处于等待状态,直到被引用的线程终止”。我认为您要完成的工作

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

于 2019-09-04T12:18:34.617 回答
-1

使用现代Java的解决方案

public void someFunction(String data) {
    smallOperation();
    new Thread(() -> {
        // doSomething long running
    }).start();
}
于 2018-12-21T15:33:23.693 回答