带有执行器框架的可调用接口。为什么即使从调用方法返回后程序也没有退出
Callable interface with executor framework. Why Program didn't exit even after returning from call method
我正在尝试了解执行程序框架的可调用接口。这是可行的,但我有点困惑为什么即使从调用方法返回后程序也不会退出。
代码:
CallableExample.java
package callable1;
import java.util.concurrent.Callable;
public class CallableExample implements Callable<String> {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
String s = Thread.currentThread().getName();
for(int i = 0 ; i < 10 ; i++)
{
s += ""+i;
System.out.println(s);
Thread.sleep(1000);
}
return s;
}
}
Tester.java
package callable1;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Tester {
public static void main(String[] args) throws Exception
{
ExecutorService pool = Executors.newFixedThreadPool(5);
Future<String> ftask = pool.submit(new CallableExample());
System.out.println("getting result");
System.out.println("----" + ftask.get());
System.out.println("main over");
}
}
java.util.concurrent.*
的线程池就是这样设计的,所以你必须在你的执行器上调用shutdown()
或shutdownNow()
。否则程序不会停止。您可以在 javadocs 中找到方法之间的区别。
我正在尝试了解执行程序框架的可调用接口。这是可行的,但我有点困惑为什么即使从调用方法返回后程序也不会退出。
代码:
CallableExample.java
package callable1;
import java.util.concurrent.Callable;
public class CallableExample implements Callable<String> {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
String s = Thread.currentThread().getName();
for(int i = 0 ; i < 10 ; i++)
{
s += ""+i;
System.out.println(s);
Thread.sleep(1000);
}
return s;
}
}
Tester.java
package callable1;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Tester {
public static void main(String[] args) throws Exception
{
ExecutorService pool = Executors.newFixedThreadPool(5);
Future<String> ftask = pool.submit(new CallableExample());
System.out.println("getting result");
System.out.println("----" + ftask.get());
System.out.println("main over");
}
}
java.util.concurrent.*
的线程池就是这样设计的,所以你必须在你的执行器上调用shutdown()
或shutdownNow()
。否则程序不会停止。您可以在 javadocs 中找到方法之间的区别。