学习过程观看视频:[狂神说Java]
https://www.bilibili.com/video/BV1B7411L7tE?p=13
欢迎大家支持噢,很良心的老师了!
三大方法,代码示例
1、newSingleThreadExecutor
package com.add;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by zjl
* 2020/11/25
**/
public class ExecutorsTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor(); //单个线程
// ExecutorService executorService = Executors.newFixedThreadPool(5); //固定大小的线程池
// ExecutorService executorService = Executors.newCachedThreadPool(); //可伸缩的,遇强则强,遇弱则弱
try {
for (int i = 0; i < 10; i++) {
// 使用了线程池之后,使用线程池来创建线程
executorService.execute(()->{
System.out.println(Thread.currentThread().getName() + "is ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 线程池用完,程序结束,关闭线程池
executorService.shutdown();
}
}
}
运行结果:
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
Process finished with exit code 0
2、newFixedThreadPool
package com.add;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by zjl
* 2020/11/25
**/
public class ExecutorsTest {
public static void main(String[] args) {
// ExecutorService executorService = Executors.newSingleThreadExecutor(); //单个线程
ExecutorService executorService = Executors.newFixedThreadPool(5); //固定大小的线程池
// ExecutorService executorService = Executors.newCachedThreadPool(); //可伸缩的,遇强则强,遇弱则弱
try {
for (int i = 0; i < 10; i++) {
// 使用了线程池之后,使用线程池来创建线程
executorService.execute(()->{
System.out.println(Thread.currentThread().getName() + "======》is ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 线程池用完,程序结束,关闭线程池
executorService.shutdown();
}
}
}
运行结果:
我们可以看到,最大可以有5个线程共同执行。
3、newCachedThreadPool
package com.add;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by zjl
* 2020/11/25
**/
public class ExecutorsTest {
public static void main(String[] args) {
// ExecutorService executorService = Executors.newSingleThreadExecutor(); //单个线程
// ExecutorService executorService = Executors.newFixedThreadPool(5); //固定大小的线程池
ExecutorService executorService = Executors.newCachedThreadPool(); //可伸缩的,遇强则强,遇弱则弱
try {
for (int i = 0; i < 10; i++) {
// 使用了线程池之后,使用线程池来创建线程
executorService.execute(()->{
System.out.println(Thread.currentThread().getName() + "======》is ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 线程池用完,程序结束,关闭线程池
executorService.shutdown();
}
}
}
执行结果:
我们可以看到,线程池会自动改变大小。