gpt4 book ai didi

java - 如何在执行线程(如分页)时获取回调

转载 作者:行者123 更新时间:2023-12-01 11:57:36 25 4
gpt4 key购买 nike

我正在使用线程和线程池。线程开始执行,在执行时,它将任务提交到线程池。线程从线程池中检索大量数据,所以我想要像分页概念这样的数据。我怎样才能实现它?

我已经实现了像下面的程序一样的回调。

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());
/*
Here code for data retrieval

*/

return "done";
}

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

}

在上面的程序中,我正在等待整个执行。我不想那样。

最佳答案

您不应等待 get() 调用完成。如果这样做,您将阻塞调用者线程。

来自JavaDocs :

Waits if necessary for the computation to complete, and then retrieves its result.

相反,类似的东西可能对您有用:

class Task1 implements Callable<String> {
private final TaskCallBack callback;

// Pass the callback to the task
public Task1(TaskCallBack callback) {
this.callback = callback;
}

@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName());
/* Here code for data retrieval */

// When the task has completed, return the result via the callback.
// This will not be in the caller thread - it will instead be async
callback.taskCompleted(result);

return "done";
}
}

并且,初始化它(并调用它):

FutureTask<String> ft = new FutureTask<>(new Task1(myCallback));
TestAsync.getPool().execute(ft);

关于java - 如何在执行线程(如分页)时获取回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28314886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com