启动线程的几种方法:(LiftOff实现Runnable接口)
1.直接在main中调用run()方法,其实不是单独线程驱动的,只有main线程;
2.Thread类
Thread t1 = new Thread(new LiftOff());
Thread t2 = new Thread(new LiftOff());
t1.start();
t2.start();
3.使用Executor
//ExecutorService exec = Executors.newCachedThreadPool();
//ExecutorService exec = Executors.newSingleThreadExecutor();
ExecutorService exec = Executors.newFixedThreadPool(2);
for(int i = 0;i<5;i++){
exec.execute(new LiftOff());
}
CachedThreadPool将为每一个任务都创建一个线程,通常会创建与所需数量相同的线程,然后在他回收旧线程时停止创建新线程,因此是合理的Executos的首选。其他可考虑FixedThreadPool或者SingleThreadExecutor;
SingleThreadExecutor像是FixedThreadPool数量为1,但是还提供了一种重要的并发保证,其他线程不会被并发调用。