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

泽库网站制作公司哪家好,找创新互联!从网页设计、网站建设、微信开发、APP开发、响应式网站设计等网站项目制作,到程序开发,运营维护。创新互联2013年开创至今到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联。
无论是接收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 {
 - ExecutorService es = Executors.newSingleThreadExecutor();
 - Future fr = es.submit(new RunnableTest());// 提交任务
 - Future fc = 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 {
 - ExecutorService es = Executors.newSingleThreadExecutor();
 - Future fr = es.submit(new RunnableTest());// 提交任务
 - Future fc = 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()方法停止服务,否则其中的所有线程都会保持运行,程序不会退出。
Copyright © 2009-2022 www.wtcwzsj.com 青羊区广皓图文设计工作室(个体工商户) 版权所有 蜀ICP备19037934号