Java多线程一直是java基础中非常重要的一环,最近自己在复习时,发现对其又有了新的了解,Executor可以很方方便的管理多线程,在这把它的三种不同的线程池贴出来做一个记录,有兴趣的可以看看
Executor
package chapter21.task;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Executors的使用:
*/
public class CacheedThreadPool {
public static void main(String[] args) {
//CachedThreadPool
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
exec.execute(new LiftOff());
}
//shutdown()方法:防止新任务被提交给Executor,当前线程继续运行在shutdown()被调用之前提交的所有任务,这个程序将在Executor中所有任务完成之后矜尽快退出
exec.shutdown();
//FixedThreadPool:有限的线程集执行所有提交的任务:在创建的时候就一次性预先执行代价高昂的线程分配
ExecutorService execFix = Executors.newFixedThreadPool(5);
//备注:CachedThreadPool通常会创建与所需数量相同的线程,然后在它回收旧线程的时候停止创建新线程,因此它是合理的Executor的首选,专辑由当这种方式会引发问题的时候,才需要切换到FixedThreadPool
//SingleThreadExecutor:就是线程数量为1的FixedThreadPool,如果向他提供了多个任务,那么这些任务会排队,所有任务会使用相同的线程 SingleThreadExecutor会序列化所有提交给他的任务,并会维护他自己【隐藏】的悬挂任务队列
ExecutorService execSing = Executors.newSingleThreadExecutor();
}
}
另外,还有一种实现Callable接口的,可以有个任务返回值
package chapter21.task;
import java.util.ArrayList;
import java.util.concurrent.*;
public class CallableDemo {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<>();
for (int i = 0; i < 10; i++) {
results.add(exec.submit(new TaskWithResult(i)));
}
for (Future<String> fs:results){
try{
System.out.println(fs.get());
}catch (InterruptedException e){
System.out.println(e);
return;
}catch (ExecutionException e){
System.out.println(exec);
}finally {
exec.shutdown();
}
}
}
}
/**
* Callable:任务执行完成能够返回一个值
*/
class TaskWithResult implements Callable {
private int id;
public TaskWithResult(int id) {
this.id = id;
}
@Override
public String call() {
return "result of TaskWithResult" + id;
}
}
重点是理解Future的作用,以后有时间再给大家补上