Future 实例

来源:互联网 发布:windows me 系统安装 编辑:程序博客网 时间:2024/05/17 20:27
package com.hao947.P004.java.ThreadCallableFuture;import java.util.concurrent.Callable;import java.util.concurrent.FutureTask;public class ThirdThread implements Callable<Integer> {public static void main(String[] args) {// TODO Auto-generated method stub// 创建Callable对象ThirdThread thirad = new ThirdThread();// 使用FutureTask来包装Callable对象FutureTask<Integer> task = new FutureTask<>(thirad);for (int i = 0; i < 100; i++) {System.out.println(Thread.currentThread().getName() + "的循环变量的值:"+ i);if (i == 20) {// 实质还是以Callable对象来创建并发启动线程new Thread(task, "返回值得线程").start();}}// 获取线程的返回值try {System.out.println("子线程的返回值:" + task.get());} catch (Exception e) {e.printStackTrace();}}@Override// 实现call()方法,作为线程主体public Integer call() {// TODO Auto-generated method stubint i = 0;for (; i < 100; i++) {System.out.println(Thread.currentThread().getName() + "的循环变量的值:"+ i);}return i;}}

原创粉丝点击