import org.junit.Test;
import java.util.concurrent.*;
/**
* @author peter
* 2019/1/4 16:58
*/
public class ThreadTest {
@Test
public void test() throws InterruptedException, ExecutionException {
long l = System.currentTimeMillis();
ExecutorService service = Executors.newCachedThreadPool();
Future<Integer> submit = service.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName());
//业务一
Thread.sleep(3000);
//返回执行的结果集
return 1;
}
});
//业务二
Thread.sleep(3000);
/**
* 1、应该在业务二之后在调用get(),否则主线程会一直阻塞,等待子线程的执行完返回结果
*
* 2、子线程执行后获取的结果,如果不使用get()则线程是非阻塞的
*
* **/
Integer o = submit.get();
System.out.println(Thread.currentThread().getName() + "子线程返回的结果:"+o);
System.out.println(Thread.currentThread().getName() +"总耗时:" + (System.currentTimeMillis() - l));
}
@Test
public void test1() throws InterruptedException {
long l = System.currentTimeMillis();
//业务一
Thread.sleep(3000);
//业务二
Thread.sleep(3000);
System.out.println("总耗时:"+(System.currentTimeMillis() - l));
}
}
结果:
test():
pool-1-thread-1
main子线程返回的结果:1
main总耗时:3013
test1():
总耗时:6002