Java线程池ThreadPoolExecutor

 #线程常用方法
 System.currentTimeMillis()	用于获取当前系统时间,以毫秒为单位
 start()  启动线程
 run()  线程占用CPU时执行的方法
 getState()          获取线程的状态
 setName()  设置线程名称
 getName(  )  获取线程名称
 setPirority()  设置线程的优先级参数的数字越大表示优先级越高(0~10)
 currentThread()  获取当前占用CPU的线程 ,静态方法
 sleep()  线程  休眠
 interrupt()  唤醒休眠的线程
package com.springboot.controller;


import java.util.List;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.*;

public class TestThreadPoolExecutor {
    public static void main(String[] args) throws InterruptedException {
        Random random = new Random();
        List<Integer> list = new Vector<>();
        for (int i = 1; i <= 100; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    list.add(random.nextInt());
                }
            };
            thread.start();
            thread.join();
        }
        System.out.println(list.size());
        // Executors自带线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        ExecutorService executorService1 = Executors.newFixedThreadPool(20);
        ExecutorService executorService2 = Executors.newSingleThreadExecutor();
        // 自定义线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,20,60L, TimeUnit.MICROSECONDS,new LinkedBlockingQueue<>());
        List<Integer> lists = new Vector<>();
        long start = System.currentTimeMillis();
        for (int i = 1; i <= 5000000; i++) {
            executorService.execute(() -> lists.add(random.nextInt()));
        }
        System.out.println("消耗时间" + (System.currentTimeMillis() - start) / 1000 + "\n" + "大小:" + lists.size());
    }
}

class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "===" + i);
    }
    int i = 0;

    public MyTask(int i) {
        this.i = i;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值