多線程獲取返回值

線程類:

import java.util.concurrent.Callable;
/**
 * 線程類,需要返回值的 ,實現Callable接口
 * @author xhc
 *
 */
@SuppressWarnings("rawtypes")
public class MyThread implements Callable{

	@SuppressWarnings("static-access")
	@Override
	public Object call() throws Exception {
		Thread.currentThread().sleep(1000);//睡眠一秒
		return Thread.currentThread().getName();
	}

	
}

測試類:

package com.xjiuge.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class App {
	//建立線程池
	static ExecutorService pool = Executors.newCachedThreadPool();
	
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		//存放future的集合
		List<Future<String>> list = new ArrayList<>();
		
		long st = System.currentTimeMillis();//開始時間
		//循環5次,開啓5個線程
		for (int i = 0; i < 5; i++) {
			//獲取線程類返回的值,用future接收
			Future<String> future = pool.submit(new MyThread());
			//將future放入list
			list.add(future);
		}
		
		try {
			//遍歷list讀取future中的值
			for (Future<String> future : list) {
				while(true) {
					//判斷線程操作是否執行完畢,並且操作沒有被取消掉
					if(future.isDone() && !future.isCancelled()) {
						//調用get方法獲取返回值
						String result = future.get().toString();
						System.out.println(result);
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		long et = System.currentTimeMillis();//結束時間
		System.out.println("總耗時:" + (et - st) + "ms");
	}
}

打印結果:

pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
總耗時:1004ms

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章