Java Future将停止其余的程序执行
我试图从主线程并行执行2个作业,但如果回调方法需要很长时间才能给出响应,那么其余的请求将暂停并等待首先完成 这是我的密码:Java Future将停止其余的程序执行,java,multithreading,future,executorservice,Java,Multithreading,Future,Executorservice,我试图从主线程并行执行2个作业,但如果回调方法需要很长时间才能给出响应,那么其余的请求将暂停并等待首先完成 这是我的密码: private final ExecutorService executorService = Executors.newFixedThreadPool(10); private void executeService(String uuid) { System.out.println("query executed done: " + uuid); }
private final ExecutorService executorService = Executors.newFixedThreadPool(10);
private void executeService(String uuid) {
System.out.println("query executed done: " + uuid);
}
private String getAsynchTest(final String uuid) throws Exception {
testAsynchF = executorService.submit(
new Callable<String>() {
public String call() throws Exception {
executeService(uuid);
return getFutuerResult(uuid, Thread.currentThread()); // long processing
}
});
return testAsynchF.get();
}
public String getFutuerResult(String uuid, Thread t) {
String dummy = "your result for request: "+uuid;
if (uuid.equalsIgnoreCase("112")) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return dummy;
}
public static void main(String[] args) {
SynchronousTimeoutTester tester = new SynchronousTimeoutTester();
try {
String one = "112"
System.out.println("Result sync call:*** " + tester.getAsynchTest(one));
String two = "115";
System.out.println("Result sync call:**** " + tester.getAsynchTest(two));
} catch (Exception e) {
System.out.println("catched as Exception: " + e);
}
}
private final ExecutorService ExecutorService=Executors.newFixedThreadPool(10);
私有void executeService(字符串uuid){
System.out.println(“执行的查询已完成:+uuid”);
}
私有字符串getAsynchTest(最终字符串uuid)引发异常{
testAsynchF=executorService.submit(
新的可调用(){
公共字符串调用()引发异常{
执行服务(uuid);
返回GetFutureResult(uuid,Thread.currentThread());//长处理
}
});
返回testAsynchF.get();
}
公共字符串getFutureResult(字符串uuid,线程t){
String dummy=“请求的结果:”+uuid;
if(uuid.equalsIgnoreCase(“112”)){
试一试{
t、 join();
}捕捉(中断异常e){
e、 printStackTrace();
}
}
返回假人;
}
公共静态void main(字符串[]args){
SynchronousTimeoutTester tester=新的SynchronousTimeoutTester();
试一试{
字符串一=“112”
System.out.println(“结果同步调用:**”+tester.getAsynchTest(一个));
字符串2=“115”;
System.out.println(“结果同步调用:**”+tester.getAsynchTest(两个));
}捕获(例外e){
System.out.println(“捕获为异常:+e);
}
}
如果请求112线程处于暂停状态,为什么会停止执行请求115?因为您将
线程.currentThread()
传递给getFutureResult
,并且该方法在其线程参数上调用join()
(如果uuid为“112”),该方法将等待自己的线程结束,它不能,因为它正在等待。这不会编译。。。具体来说,executeService(String)
和getFutureResult(String)
的实现是什么?executeService方法未列出,getFutureResult需要一个线程参数,maintester中有一行缺少分号。shutdown()也未指定删除该shutdown方法调用。。问题更新了。如果我想暂停请求112进行测试并允许请求115继续,那么我应该在哪里添加此联接?如果您想同时执行多个作业,但不关心结果的顺序,并且希望在结果出现时处理结果,我建议您查看CompletionService
s。你们能告诉我如何在回调方法中休眠任何请求(ex=112)的线程吗?