JAVA_创建线程任务获取任务返回结果FutureTask

JAVA_创建线程任务获取任务返回结果FutureTask

1.实现Callable接口类

package com.lius.futureTask;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
//创建Callable接口实现类
public class callableClass implements Callable {

	private List listInt = null;
	
	public callableClass(List listInt) {
		super();
		this.listInt = listInt;
	}
	@Override
	public Long call() throws Exception {
		// TODO Auto-generated method stub
		return listInt.stream().collect(Collectors.counting());
	}

}

2.创建FutureTask线程任务

package com.lius.futureTask;

import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.logging.Logger;
//FutureTask  执行线程,线程执行完毕返回执行结果(可用于耗时较长的任务,增加系统流畅度)
public class futureTask {
	
	private Logger logger = Logger.getLogger(Thread.currentThread().getName());
	public void start() {
		
		callableClass callableClass = new callableClass(Arrays.asList(1,3,5,6,7,8,11,21));
		FutureTask future = new FutureTask(callableClass);   
		new Thread(future).start();
		try {
			logger.info(future.get().toString());
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}

3.测试代码

package com.lius.test;

import org.junit.Test;

import com.lius.futureTask.futureTask;
//测试类
public class testFutureTask {

	@Test
	public void test01() {
		new futureTask().start();
	}
}

4.测试结果

七月 25, 2020 12:37:38 上午 com.lius.futureTask.futureTask start
信息: 8

 

你可能感兴趣的:(JAVA,thread,java)