代码:
public class TestExecutor {
public static void main(String[] args) {
//ExecutorService es = Executors.newFixedThreadPool(2); //并发两个线程正在执行
ExecutorService es = Executors.newCachedThreadPool(); //开多少个线程 保留多少个线程 即有多少个线程正在运行
Runnable r1 = new Runnable(){
public void run(){
for(int i = 1 ; i <= 100 ; i++){
System.out.println("### "+i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Runnable r2 = new Runnable(){
public void run(){
for(int i = 1 ; i <= 100 ; i++){
System.out.println("$$$ "+i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Runnable r3 = new Runnable(){
public void run(){
for(int i = 1 ; i <= 100 ; i++){
System.out.println("*** "+i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
//将Runnable提交给线程池,让线程池去帮我们分配线程去运行
es.submit(r1);
es.submit(r2);
es.submit(r3);
es.shutdown();
}
}
线程池相较于Thread类 Runnable接口创建线程的优点
1、避免重复创建/销毁线程,
2、一个线程反复执行多个任务。
创建线程的方式就不是Runnable对象去构建Thread对象,而是将Runnable对象提交给线程池,让线程池分配线程去运行。