ue<Runnable> workQueue=new ArrayBlockingQueue(5);//最多5等待的任务
ThreadPoolExecutor executor=new ThreadPoolExecutor(5,10,10,TimeUnit.SECONDS,workQueue);
//灵活:
for(int i=0;i<25;i++){
executor.submit(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName()+"~~~~~~~~~~~~~~~");
}
});
}
}
}
7. Callable创建线程
package demo09;
import demo03.My;
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// MyCallable myCallable=new MyCallable();
// FutureTask<Integer> task=new FutureTask<Integer>(myCallable);//把线程任务封装到该类中,该类可以获取线程任务执行后的结果.
// Thread t=new Thread(task);
// t.start();
//
// System.out.println(task.get());
//发现线程执行非常麻烦。都使用线程池来执行任务。---不要自己创建线程对象,而是使用线程池中的对象
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> submit =executorService.submit(new MyCallable());
System.out.println(submit.get());
}
}
class MyCallable implements Callable<Integer>{
//线程任务:
public Integer call() throws Exception {
int sum=0;
for(int i=0;i<=10;i++){
sum+=i;
}
return sum;
}
}
class MyRunnable implements Runnable{
public void run() {
}
}