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
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