package com.robinboot.facade.test;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.*;
/**
* @auther: TF12778
* @date: 2020/4/9 16:03
* @description:
*/
public class LJFutureTask extends LJTest {
private final ExecutorService es = new ThreadPoolExecutor(8, 10, 100, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(5000));
@Test
public void getFutureRandomNumTest() {
// 利用Future獲取隨機數
Future<Integer> ft = es.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int num = new Random().nextInt(10);
TimeUnit.SECONDS.sleep(num);
return num;
}
});
try {
int num = ft.get();
System.out.println(num);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("########################");
}
@Test
public void futureTaskSumTest() {
// 利用FutureTask獲取隨機數之和
Map<String, Future<Integer>> futureMap = new HashMap<>();
for (int i = 0; i < 10; i++) {
Future<Integer> fture = es.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int num = new Random().nextInt(10);
// TimeUnit.SECONDS.sleep(num);
return num;
}
});
futureMap.put(i + "", fture);
}
int sum = 0;
for (int i = 0; i < 10; i++) {
Future<Integer> integerFuture = futureMap.get(i + "");
try {
sum = sum + integerFuture.get();
System.out.println(integerFuture.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
System.out.println(sum);
}
@Test
public void getFutureTaskRandomNumTest() {
// 利用FutureTask獲取隨機數
FutureTask<Integer> ftu = new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int num = new Random().nextInt(10);
TimeUnit.SECONDS.sleep(num);
return num;
}
});
new Thread(ftu).start();
try {
int num = ftu.get();
System.out.println(num);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}