线程池的使用
无返回值的执行方法
@Test
public void test01() throws Exception
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(new MyRunnable());
Thread.sleep(3000);
}
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"线程池测试"+i);
}
}
}
有返回值的执行方法
@Test
public void test03() throws Exception{
ExecutorService threadPool = Executors.newFixedThreadPool(2);
Future<Integer> submit = threadPool.submit(new MyCallable(10));
Future<Integer> submit1 = threadPool.submit(new MyCallable(20));
System.out.println(submit.get());
System.out.println(submit1.get());
}
public class MyCallable implements Callable<Integer>{
private Integer n;
public MyCallable(Integer n) {
this.n = n;
}
@Override
public Integer call() throws Exception {
return (n*n+n)/2;
}
}