有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程后台处理java

如果这是一个基本问题,请原谅我的无知

我想了解如何从模块返回控制并在后台开始处理

让启动组件A调用组件B。组件B执行一些基本处理,启动一个后台线程,并立即将控制权返回给A。每当后台线程完成其处理时,它将把结果存储在持久性存储中。此后台线程的整个处理过程非常耗时,并且无法等待后台线程完成

Component A {
  Http Call component B
}

Component B {
  // Got request from component A
  start background thread();
  return; // don't wait till background thread finishes off
}

background thread() {
 // time consuming task
}

如何在java中实现这种行为?我不认为这是完全异步的处理形式,因为通信是通过具有超时设置的http连接进行的

更新:

 Component A:
 Receives Http call 


 Component B:

 Approach1:

 Runnable runnable = new MyThread();
 new Thread(runnable).start();

 Approach2:

 ExecutorService exec = Executors.newSingleThreadExecutor();
 exec.execute(new MyThread());
 exec.shutdown();

上述两种方法都帮助我开始后台处理,并将即时控制权返回给A


共 (3) 个答案

  1. # 1 楼答案

    假设您希望在后台处理完成之前返回HTTP调用,那么您的伪代码对Java完全有效

    在下一个详细级别,查看Javadoc中的ThreadRunnablejava.nio库类

  2. # 2 楼答案

    最简单的方法可能是使用后台处理逻辑作为参数创建一个新的java Thread

    void componentB() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // Time consuming task.
            }
        }).start();
        // The method continues without stopping.
    }
    

    在java的更高版本中,您还可以使用ForkJoinPool-类来实现这一点:

    public class Main {
    
        private final ExecutorService executor = new ForkJoinPool();
    
        void componentA() {
            componentB();
        }
    
        void componentB() {
            executor.execute(this::timeConsumingTask);
            // The method continues without stopping.
        }
    
        private void timeConsumingTask() {
            // Time consuming task.
        }
    }
    
  3. # 3 楼答案

    在原始级别使用线程对于一些简单的概念验证来说是一个很好的解决方案,但是我强烈建议至少尝试使用java中的并发API,您可以找到文档here。好的教程是here

    最简单的方法是创建一个可调用对象,其中包含要在后台执行的指令

    Callable myInstructions = new Callable<ObjectToReturn>() {
             public ObjectToReturncall() {
               return object.methodCall();
           }}
    

    使用ExecutorService提交此可调用对象以期望将来的对象

    Future<ObjectToReturn> future = executor.submit(myInstructions);
    //Do anything else as this wont be blocked ..
    

    Future API有一组方法来询问任务是否已经完成

    if(future.isDone()) // Ask if the task is done
        ObjectToReturn solution = future.get()   // Get the result
    

    使用FutureAPI非常简单

    编辑

    如果您不希望将来的api有任何响应,只需执行一个您可以使用的操作即可

    Future<Void> future = executor.submit(new Callable<Void>() {
        public Void call() throws Exception {
            testA.abc();
            return null;
        }
    });
    

    另一个选项是,如果您不想收到结果或得到响应,只需启动一个线程即可

    ExecutorService executor = Executors.newFixedThreadPool(5);`
    executor.execute(new RunnableClass());
    

    也要避免在ExecutorService上调用shutdown,直到进程结束,当你没有更多时间做的时候,在spring或container fwks中,一旦应用程序关闭,容器负责关闭ExecutorService