package thread;
import org.junit.Test;
import sun.nio.ch.ThreadPool;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.*;
public class AsyncFuture {
ThreadPoolExecutor threadPool=new ThreadPoolExecutor(
5
,10
,5
,TimeUnit.SECONDS
,new LinkedBlockingDeque<Runnable>()
);
public String getResult() throws InterruptedException {
System.out.println("子线程被调用,调用时间"+System.currentTimeMillis());
Thread.sleep(3000);
System.out.println("子线程任务结束时间"+System.currentTimeMillis());
return "结果";
}
@Test
public void futureDemo() throws Exception {
//提交线程
Future future=threadPool.submit(this::getResult);
System.out.println("提交后,主线程休眠五秒");
System.out.println("主线程开始时间"+System.currentTimeMillis());
//休眠
Thread.sleep(5000);
System.out.println("主线程结束时间"+System.currentTimeMillis());
//get():获取执行结果,重载可选参数,例:3000,TimeUnit.MILLISECONDS ↙
//在3000毫秒内获取结果,如果该时间内没有得到结果,抛出异常:TimeoutException
System.out.println(future.get()+":"+System.currentTimeMillis());
}
void d2(){
try {
Thread.sleep(2000);
System.out.println("子线程休眠完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void demo2() throws InterruptedException {
new Thread(this::d2).start();
Thread.sleep(5000);
System.out.println("主线程执行完毕");
}
}