2018-12-10 17:05:47
创建线程池
创建固定数量的线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadDemo {
public static void main(String[] args){
//创建一个固定线程数量的线程池,固定线程数量值的是线程数量上限
final ExecutorService threadPool = Executors.newFixedThreadPool(10);
//创建一个可以复用的线程池
final ExecutorService threadPool = Executors.newCachedThreadPool();
threalPool.execute(new Runnable(){
@Override
public void run(){
System.out.println("Thread name:"
+Thread.currentThread().getName()
+ "Thread id:"+ Thread.currentThread().getId());
//Alt+回车 Ctrl+Alt+T
try {
Thred.sleep(3000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
});
threadPool.shutdown(); //关闭线程池
//线程池复用
for (int i = 0; i < 10 ; i ++){
threalPool.execute(new Runnable(){
@Override
public void run(){
System.out.println("Thread name:"
+Thread.currentThread().getName
+ "Thread id:"+ Thread.currentThread().getId());
//Alt+回车 Ctrl+Alt+T
try {
Thred.sleep(3000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
});
}
System.out.println(Thread.currentThread().getName());
Thread.sleep(3000);
for (int i = 0; i < 10 ; i ++){
threalPool.execute(new Runnable(){
@Override
public void run(){
System.out.println("Thread name:"
+Thread.currentThread().getName
+ "Thread id:"+ Thread.currentThread().getId());
//Alt+回车 Ctrl+Alt+T
try {
Thred.sleep(3000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
});
}
}
}