Java多线程之Callable接口的实现

文章目录

  • 线程池管理
  • 有返回值的线程Callable接口的实现
  • 测试
  • 结果

线程池管理

package com.zfinfo;

import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
/**
 * 线程池管理
 * @author luww
 *
 */
public class MyExecutor {
	private ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
	private List<Future> futureList = new Vector<>();
	/**
	 * 提交任务
	 * @param list
	 */
	public void submit(List<String> list) {
		for (String str : list) {
			futureList.add(executor.submit(new MyCallable().init(str)));
		}
	}
	/**
	 * 获取当前活跃的线程数
	 * @return
	 */
	public int getActiveCount(){
		return ((ThreadPoolExecutor)executor).getActiveCount();
	}
	/**
	 * 执行完后关闭线程池
	 */
	public void shutdown() {
		executor.shutdown();
	}

	/**
	 * 返回任务执行结果
	 *
	 * @return
	 */
	public List<Future> getFutureList() {
		return futureList;
	}

	/**
	 * 返回线程池
	 *
	 * @return
	 */
	public ExecutorService getExecutor() {
		return executor;
	}

	/**
	 * @param threads
	 *            工作线程数量
	 * @return
	 */
	public MyExecutor setThreads(int threads) {
		this.executor = Executors.newFixedThreadPool(threads);
		return this;
	}
}

有返回值的线程Callable接口的实现

package com.zfinfo;

import java.util.concurrent.Callable;
/**
 * 有返回值的线程
 * @author luww
 *
 */
public class MyCallable implements Callable<Object> {
	private String str;

	public MyCallable init(String str) {
		this.str = str;
		return this;
	}

	@Override
	public Object call() throws Exception {
		return "call:" + str;
	}

}

测试

public static void main(String[] args) throws Exception {
		List<String> list = new ArrayList<>();
		for (int i = 0; i < 5; i++) {
			list.add(UUID.randomUUID().toString());
		}
		// 创建myExcutor实例
		MyExecutor myExecutor = new MyExecutor();
		// 提交
		myExecutor.submit(list);
		// 获取返回值
		List<Future> futureList = myExecutor.getFutureList();
		// 遍历返回值
		for (int i = 0; i < futureList.size(); i++) {
			// get() 方法会阻塞当前线程直到获取返回值
			System.out.println(i + ":" + futureList.get(i).get());
		}
		// 关闭线程池
		myExecutor.shutdown();
		System.out.println("availableProcessors:"+Runtime.getRuntime().availableProcessors());
		System.out.println("totalMemory:"+Runtime.getRuntime().totalMemory());
		System.out.println("freeMemory:"+Runtime.getRuntime().freeMemory());
		System.out.println("maxMemory:"+Runtime.getRuntime().maxMemory());
	}

结果

0:call:b49d2006-8a91-4217-8f17-db2349448897
1:call:548dba0a-0ccc-4a1f-b897-bf30c3da54c3
2:call:00b02d86-31ef-4b5b-890d-471397eef636
3:call:3c9f683f-43a8-4451-ac61-70bac41d8d7e
4:call:4b18a89f-4050-4019-a78f-e481637748da
availableProcessors:4
totalMemory:56623104
freeMemory:52973240
maxMemory:826277888

你可能感兴趣的:(Java)