public class Test {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = new ThreadPoolExecutor(3, 5, 1L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
for(int i=0;i<3;++i){
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"执行任务");
});
}
}
}
参数1:corePoolSize=3 表示核线程数为3
参数2:maximunPoolSize=5 表示最大线程数
参数3:keepAliveTime=1L
参数4:TimeUnit=TimeUnit.SECONDS
参数5:等待队列大小为3
参数6:线程构建方法
参数7:线程发送堵塞之后的策略
参数解释:
① 如果来了3个任务,那么会启动3个线程(corePoolSize=3)分别干活。
② 如果来了4个任务,则会把另外一个任务放到等待队列中等待;如果来了7个任务,这里等待队列只有大小为3,核线程数为3,那么还有一个任务怎么办,队列都放不下了,因为此时线程数<最大线程数,这时还会开一个线程干活,所有就会有4个线程在干活,3个在队列中等待;
下面下了一个多线程遍历很大的数组,并行处理,可以实现吗??
public class Test {
public static void main(String[] args) throws InterruptedException {
int count = 100000;
int[] intList = new int[count];
for (int i=1;i<count;++i) {
intList[i] = i;
}
//设置核线程数为20
//分配线程,按照平均分配,每个线程处理的任务固定,每个线程处理count/coreSize个任务
int coreSize=20;
int gap = count/coreSize;
ExecutorService executorService = new ThreadPoolExecutor(coreSize, coreSize+10, 1L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
for(int i=0;i<coreSize;++i){
int finalI = i;
executorService.execute(()->{
//这里是任务入口
test22(intList,finalI *gap,(finalI +1)*gap);
});
}
while(true){
}
}
private static void test22(int[] list,int start, int end) {
System.out.println(start);
System.out.println(end);
}
}
类重写run方法实现多线程例子:
等待主线程执行完毕的方式:习惯性使用
CountDownLatch
public static void main(String[] args) throws InterruptedException {
int coreSize = 50;
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(coreSize);
final CountDownLatch latch= new CountDownLatch(50);//使用java并发库concurrent
for(int i=0;i<coreSize;i++) {
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
//j是线程内部变量,每个线程都有一份,自己会管理,不会冲突
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程执行!" + Thread.currentThread().getName());
latch.countDown();//让latch中的数值减一
}
});
}
latch.await();//阻塞当前线程直到latch中数值为零才执行
//这里的sysout输出是在main线程中的,其list的size根据当时这个list的情况只输出一次,可能是任意小于500的值
System.out.println("主线程执行...");
}