JUC_02
线程池
好处:
a、降低资源的消耗
b、提高响应速度
c、方便管理
Integer.max(正负21亿)
三大方法
点击查看代码
package org.li;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool {
public static void main(String[] args) {
//三大方法
///ExecutorService threadPoll= Executors.newSingleThreadExecutor();
//ExecutorService threadPoll= Executors.newFixedThreadPool(10);
ExecutorService threadPoll= Executors.newCachedThreadPool();
try {
for(int i=0;i<100;i++){
threadPoll.execute(()->{
System.out.println(Thread.currentThread().getName()+"ok");
});
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
threadPoll.shutdown();
}
//7大参数
}
}
7大参数
corePoolSize
maximumPoolSize
keepAliveTime
unit
workQueue
Executors.defaultThreadFactory()
defaultHandler
点击查看代码
package org.li;
import java.util.concurrent.*;
public class ThreadPool {
public static void main(String[] args) {
//三大方法
///ExecutorService threadPoll= Executors.newSingleThreadExecutor();
//ExecutorService threadPoll= Executors.newFixedThreadPool(10);
//ExecutorService threadPoll= Executors.newCachedThreadPool();
ExecutorService threadPoll= new ThreadPoolExecutor(2
, 5
, 3
, TimeUnit.SECONDS
, new LinkedBlockingQueue<>(3)
,Executors.defaultThreadFactory()
, new ThreadPoolExecutor.AbortPolicy()); //线程池满了,多的就报错
//CallerRunsPolicy //哪里来的去哪里
//DiscardPolicy //队列满了,不会抛出异常,
//DiscardPolicy //队列满了,不会抛出异常,
//ThreadPoolExecutor.DiscardOldestPolicy() 满了之后会尝试和第一个竞争
try {
for(int i=0;i<8;i++){
threadPoll.execute(()->{
System.out.println(Thread.currentThread().getName()+"ok");
});
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
threadPoll.shutdown();
}
//7大参数
}
}

浙公网安备 33010602011771号