java - 如何保持线程执行直到异步线程返回回调

标签 java multithreading concurrency parallel-processing executorservice

我的场景如下图所示

enter image description here

这里的主线程是我的java应用程序。它打开一个WM线程来执行。 WM 处理任务执行。他需要调用任务号来执行。 假设它包含任务T1,T2,T3

T3 依赖于 T2,T2 依赖于 T1。 WM首先调用RM执行T1的任务执行。 T1可以在寻呼中响应,也可以在T1完成后响应。

问题是如何等待T1完成然后开始T2的执行。当T1部分完成发送分页数据时如何通知WM。

这是简单的场景,但在 T1、T2、T3、T4 的情况下。 T3依赖于T1和T2。

代码:

public class TestAsync implements TaskCallBack {
    public static ExecutorService exService = Executors.newFixedThreadPool(5);
    public static void main(String args[]) throws InterruptedException, ExecutionException{
        Task t1 = new Task();
        t1.doTask(new TestAsync());

    }

    public static ExecutorService getPool(){
        return exService;
    }

    @Override
    public void taskCompleted(String obj) {
        System.out.println(obj);
    }
}

class Task {
 public void doTask(TaskCallBack tcb) throws InterruptedException, ExecutionException{
     FutureTask<String> ft = new FutureTask<>(new Task1());
     TestAsync.getPool().execute(ft);
     tcb.taskCompleted(ft.get());
 }

}

class Task1 implements Callable<String>{

    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName());               
        return "done";
    }

  interface TaskCallBack{
      public void TaskCompleted(String obj);
  }

}

最佳答案

这是一个非常有趣的话题。我在开发高度并行的网络数据包处理解决方案时遇到了类似的问题。我将分享我的发现,但在此之前我应该​​说,对任何并行系统使用某种临时解决方案总是一个坏主意。

如果没有适当的架构支持,调试、优化和进一步开发可能会变成一场噩梦。假设我们有三个相关任务:

enter image description here

第一个解决方案

将引入composite或compound task抽象,让依赖的任务按正确的顺序执行,摆脱延迟、等待/阻塞、复杂的任务管理等

enter image description here

我将使用简化的代码来说明这种方法:

/**
 * Defines a high-level task contract. 
 * Let's pretend it is enough to have it this simple.
 */
interface Task extends Runnable {

}

/**
 * Defines a simple way to group dependent tasks.
 * 
 * Please note, this is the simplest way to make sure dependent tasks will be
 * executed in a specified order without any additional overhead.
 */
class CompoundTasks implements Task {

    private List<Task> tasks = ...;

    public void add(Task task) {
        tasks.add(task);
    }

    @Override
    public void run() {
        for(Task t : tasks) {
           t.run();
        }
    }        
}

第二种方案

将让任务具有明确的依赖关系,并让执行者意识到这一点。基本上,规则很简单——如果任务有 Unresolved 依赖关系,它应该被推迟。这种方法可以很容易地实现并且工作得很好。

enter image description here

请注意,由于需要一些资源来验证任务、管理队列等,第二种解决方案将引入微小的性能损失。

让我们改进基于任务的方法:

/**
 * Defines yet another abstraction to make dependencies 
 * visible and properly tracked. 
 * 
 */
abstract class DependentTask implements Task {

    private List<DependentTask> dependencies = ...;

    public void addDependency(DependentTask task) {
        dependencies.add(task);
    }

    /**
     * Verifies task can be processed. 
     */
    public boolean hasDependenciesResolved() {
        boolean result = true;
        for(DependentTask t : dependencies) {
            if(!t.hasDependenciesResolved()) {
                result = false;
                break;
            }
        }
        return result;
    }

    @Override
    public abstract void run();
}

/**
 * Implements a very basic queue aware of task dependencies.
 * 
 * Basically, the idea is just to avoid any blocking state. If task can't
 * be processed (because of unresolved dependencies) it should be 
 * postponed and verified later.
 */
class TaskQueue<T extends DependentTask> implements Runnable {        
    private Queue<T> queue = ...;

    @Override
    public void run() {
        while(true) {
            if(!queue.isEmpty()) {

                T task = queue.poll();

                // Verify all dependencies have been resolved.
                if(task.hasDependenciesResolved()) {
                    task.run();         // process task if there is no unresolved
                                        // dependencies
                }else{
                    queue.add(task);    // return task to the queue
                }

            }else{
                // sleep for some reasonable amount of time
            }
        }
    }        
}

这两种方法都很容易追踪,因此您始终能够了解正在发生的事情。

关于java - 如何保持线程执行直到异步线程返回回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378933/

相关文章:

java - 删除除连字符之外的所有特殊字符

java - 使用 jpql 和 jpa 从日期字段中提取年份

java - 由于超时而安全取消线程

php - 处理相同的函数同时运行和处理相同的数据

c++ - 并发写入 std::vector 到不同的索引会导致崩溃?

java - 将对象传递给方法时出现意外输出

java - 如何在 SPRING 中捕获 Hibernate SQL 异常

javascript - 单线程 Javascript 中的 AJAX 实现

JavaFX listview 使用线程在自定义单元格中加载错误的图像

java - 为什么由 ScheduledExecutorService.schedule() 启动的线程永远不会终止?