Java线程池需要不断的学习,在学习的时候我们就要注意不少的问题。下面我们就来看看具体的语言运作环境如何才能满足Java线程池相关程序的运行。希望大家有所收获。

无论是接收Runnable型参数,还是接收Callable型参数的submit()方法,都会返回一个Future(也是一个接口)类型的对象。该对象中包含了任务的执行情况以及结果。调用Future的boolean isDone()方法可以获知任务是否执行完毕;调用Object get()方法可以获得任务执行后的返回结果,如果此时任务还没有执行完,get()方法会保持等待,直到相应的任务执行完毕后,才会将结果返回。

我们用下面的一个例子来演示Java5.0中Java线程池的使用:

Java代码

import java.util.concurrent.*;
public class ExecutorTest {
public static void main(String[] args) throws
InterruptedException,
ExecutionException {
ExecutorServicees=Executors.newSingleThreadExecutor();
Futurefr=es.submit(new RunnableTest());// 提交任务
Futurefc=es.submit(new CallableTest());// 提交任务
// 取得返回值并输出
System.out.println((String) fc.get());
// 检查任务是否执行完毕
if (fr.isDone()) {
System.out.println("执行完毕-RunnableTest.run()");
} else {
System.out.println("未执行完-RunnableTest.run()");
}
// 检查任务是否执行完毕
if (fc.isDone()) {
System.out.println("执行完毕-CallableTest.run()");
} else {
System.out.println("未执行完-CallableTest.run()");
}
// 停止线程池服务
es.shutdown();
}
}
class RunnableTest implements Runnable {
public void run() {
System.out.println("已经执行-RunnableTest.run()");
}
}
class CallableTest implements Callable {
public Object call() {
System.out.println("已经执行-CallableTest.call()");
return "返回值-CallableTest.call()";
}
}
import java.util.concurrent.*;
public class ExecutorTest {
public static void main(String[] args) throws
InterruptedException,
ExecutionException {
ExecutorServicees=Executors.newSingleThreadExecutor();
Futurefr=es.submit(new RunnableTest());// 提交任务
Futurefc=es.submit(new CallableTest());// 提交任务
// 取得返回值并输出
System.out.println((String) fc.get());
// 检查任务是否执行完毕
if (fr.isDone()) {
System.out.println("执行完毕-RunnableTest.run()");
} else {
System.out.println("未执行完-RunnableTest.run()");
}
// 检查任务是否执行完毕
if (fc.isDone()) {
System.out.println("执行完毕-CallableTest.run()");
} else {
System.out.println("未执行完-CallableTest.run()");
}
// 停止线程池服务
es.shutdown();
}
}
class RunnableTest implements Runnable {
public void run() {
System.out.println("已经执行-RunnableTest.run()");
}
}
class CallableTest implements Callable {
public Object call() {
System.out.println("已经执行-CallableTest.call()");
return "返回值-CallableTest.call()";
}
}

运行结果:

已经执行-RunnableTest.run()
已经执行-CallableTest.call()
返回值-CallableTest.call()
执行完毕-RunnableTest.run()
执行完毕-CallableTest.run()

使用完Java线程池后,需要调用它的shutdown()方法停止服务,否则其中的所有线程都会保持运行,程序不会退出。