四种策略、五种状态、六个核心参数、七种阻塞队列

四种策略、五种状态、六个核心参数、七种阻塞队列

private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
//表示一个int型占用32位，减去3位表示29位
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

//将-1左移29位后变成111
private static final int RUNNING    = -1 << COUNT_BITS;
//将0左移29位后是000
private static final int SHUTDOWN   =  0 << COUNT_BITS;
//将0左移29位后是001
private static final int STOP       =  1 << COUNT_BITS;
//将0左移29位后是010
private static final int TIDYING    =  2 << COUNT_BITS;
//将0左移29位后是011
private static final int TERMINATED =  3 << COUNT_BITS;


// 重点在阻塞队列上
return new FinalizableDelegatedExecutorService
0L, TimeUnit.MILLISECONDS,
}


/**
* Author:   苏州程序大白
* Date:     2021/4/17 9:00
* Description: 但线程的线程池
*/

static {
}

public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
final int temp = i;
@Override
public void run() {
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}


// 指定线程数
0L, TimeUnit.MILLISECONDS,
}

// 执行线程数和线程工厂类
0L, TimeUnit.MILLISECONDS,
}


public class FixedThreadPool {

static {
//初始化固定核心线程数的线程池
}

public static void main(String[] args) throws Exception {
for (int i = 0; i < 20; i++) {
final int temp = i;
@Override
public void run() {
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
System.out.println("*********************");
}
}


public ScheduledThreadPoolExecutor(int corePoolSize,
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
}


public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit) {}
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit) {}


public class ScheduledThreadPool {

static {
//初始化固定核心线程数的线程池
}

public static void main(String[] args) throws Exception {
for (int i = 0; i < 5; i++) {
final int temp = i;
@Override
public void run() {
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 3, 10, TimeUnit.SECONDS);
}

}
}


public static ExecutorService newCachedThreadPool() {
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
//可自定义线程工厂类构造
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
}


public class CachedThreadPool {

static {
//初始化带有缓存的线程池
}

public static void main(String[] args) throws Exception {
for (int i = 0; i < 5; i++) {
final int temp = i;
@Override
public void run() {
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}


1.FixedThreadPool和SingleThreadPool:允许的请求队列长度为 Integer.MAX_VALUE，可能会堆积大量的请求，导致OOM


new ThreadPoolExecutor(“核心线程数”, “最大线程数”, “空闲线程存活时间”, “时间单位”, “阻塞队列类型”);


1.CPU（计算）密集型

public class ThreadPoolTest {
// 初始一个线程池

//计算线程池运行总时长

//单个线程运行市场

static {
// 用于获取当前硬件设备的CPU核心数
int coreNum = Runtime.getRuntime().availableProcessors();
System.out.println("当前设备CPU核心数：" + coreNum);

// 这里是重点，通过修改核心线程数和最大线程数，来观察任务执行耗时变化，即可证明前面阐述的理论
}

public static void main(String[] args) throws Exception {
//运行总次数可以不修改
int testNum = 100;
for (int i = 0; i < testNum; i++) {
//提交一个计算密集型任务，并计算单个任务总耗时

//提交一个IO密集型任务，并计算单个任务总耗时
}

for (Future<?> future : futureTaskList) {
//获取线程执行结果
future.get(testNum, TimeUnit.SECONDS);
}

}

public static Long getTime(Vector<Long> list) {
long time = 0;
for (int i = 0; i < list.size(); i++) {
time = list.get(i) + time;
}
return time;
}
}

/**
* FileName: TestCPU
* Author:   苏州程序大白
* Date:     2021/4/17 9:00
* Description: 计算密集型任务
*/
public class TestCPU implements Runnable {
private long startTime = 0;

startTime = System.currentTimeMillis();
}

@Override
public void run() {
long start = System.currentTimeMillis();
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
//统计1~100000之间素数的总数
countPrimes(1, 100000);
long endTime = System.currentTimeMillis();

long threadPoolTime = endTime - startTime;
long threadTime = endTime - start;

System.out.println("当前线" + Thread.currentThread().getName() + "程耗时：" + (endTime - start) + " ms");
}

/**
* 判断是否为素数
*/
public boolean isPrime(final int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

/**
* 计算素数
*/
public int countPrimes(final int startNum, final int endNum) {
int count = 0;
for (int i = startNum; i <= endNum; i++) {
if (isPrime(i)) {
count++;
}
}
return count;
}
}


2.I/O密集型

/**
* FileName: TestIO
* Author:   苏州程序大白
* Date:     2021/4/17 9:00
* Description: IO密集型任务
*/
public class TestIO implements Runnable {
private long startTime = 0;

startTime = System.currentTimeMillis();
}

@Override
public void run() {
long start = System.currentTimeMillis();
try {
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
// 执行IO操作
} catch (IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("当前线程" + Thread.currentThread().getName() + "耗时：" + (end - start) + " ms");
}

/**
* IO操作,读取一个本地文件
*/
public void readFile() throws IOException {
//自己随便创建一个txt文件用来测试
File sourceFile = new File("/Users/RollerRunning/Documents/test/IO.txt");
//按行读取
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
}
}


public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool
(parallelism,
null, true);
}

public static ExecutorService newWorkStealingPool() {
return new ForkJoinPool
(Runtime.getRuntime().availableProcessors(),
null, true);
}


public class WorkStealThreadPool {

static {
//初始化无锁线程池
}

public static void main(String[] args) throws Exception {
int core = Runtime.getRuntime().availableProcessors();
System.out.println("当前设备CPU核心数为：" + core);
for (int i = 0; i < 50; i++) {
@Override
public String call() {
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}

• 1
点赞
• 2
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

01-21 829

08-10 1万+
07-15 11
07-30 5451
08-07 163
02-25 2804
04-14 6883
01-20 58
04-24 1678
09-29 1万+

¥2 ¥4 ¥6 ¥10 ¥20

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