线程池
package 多线程;
import java.util.concurrent.*;
/**
* 线程池表示的是可以利用框架控制多个线程的使用,也就是不用自己new多个Thread线程
*/
class TestnewCachedThreadPool{
//无限创建多个线程
public void test(){
ExecutorService executorService=Executors.newCachedThreadPool();
for(int x=0;x<10;x++){
//创建10个线程
executorService.submit(()->{
System.out.println(Thread.currentThread().getName());
});
}
executorService.shutdown();
}
}
class TestnewSingleThreadExecutor{
//创建1个线程,10个任务交给一个线程
public void test(){
ExecutorService executorService=Executors.newSingleThreadExecutor();
for(int x=0;x<10;x++){
//创建1个线程
executorService.submit(()->{
System.out.println(Thread.currentThread().getName());
});
}
executorService.shutdown();
}
}
class TestnewFixedThreadPool{
//创建固定的线程数
public void test(){
ExecutorService executorService=Executors.newFixedThreadPool(2);
for(int x=0;x<10;x++){
//创建1个线程
executorService.submit(()->{
System.out.println(Thread.currentThread().getName());
});
}
executorService.shutdown();
}
}
class TestnewScheduledThreadPool{
//创建定时调度器
public void test(){
ScheduledExecutorService executorService=Executors.newScheduledThreadPool(5);
for(int x=0;x<10;x++){
//延迟3秒后 每2秒创建5个线程,
executorService.scheduleAtFixedRate(()->{
System.out.println(Thread.currentThread().getName());
},3,2,TimeUnit.SECONDS);
}
}
}
public class ThreadPool {
public static void main(String args[]){
// TestnewCachedThreadPool testnewCachedThreadPool=new TestnewCachedThreadPool();
// testnewCachedThreadPool.test();
// TestnewSingleThreadExecutor testnewSingleThreadExecutor=new TestnewSingleThreadExecutor();
// testnewSingleThreadExecutor.test();
// TestnewFixedThreadPool testnewFixedThreadPool=new TestnewFixedThreadPool();
// testnewFixedThreadPool.test();
TestnewScheduledThreadPool testnewScheduledThreadPool=new TestnewScheduledThreadPool();
testnewScheduledThreadPool.test();
}
}