线程池是什么?Java四种线程池的使用介绍( 三 )


运行程序做稍微修改:
01package test;02import java.util.concurrent.ExecutorService;03import java.util.concurrent.Executors;04public class ThreadPoolExecutorTest {05public static void main(String[] args) {06ExecutorService singleThreadExecutor = Executors.newCachedThreadPool();07for (int i = 0; i < 100; i) {08final int index = i;09singleThreadExecutor.execute(new Runnable() {10public void run() {11try {12while(true) {13System.out.println(index);14Thread.sleep(10 * 1000);15}16} catch (InterruptedException e) {17e.printStackTrace();18}19}20});21try {22Thread.sleep(500);23} catch (InterruptedException e) {24e.printStackTrace();25}26}27}28}复制代码package test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadPoolExecutorTest {public static void main(String[] args) {ExecutorService singleThreadExecutor = Executors.newCachedThreadPool();for (int i = 0; i < 100; i) {final int index = i;singleThreadExecutor.execute(new Runnable() {public void run() {try {while(true) {System.out.println(index);Thread.sleep(10 * 1000);}} catch (InterruptedException e) {e.printStackTrace();}}});try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}}}}效果如下:

线程池是什么?Java四种线程池的使用介绍

文章插图
选择我们运行的程序:
线程池是什么?Java四种线程池的使用介绍

文章插图
监控运行状态
关于Java四种线程池的使用技巧就给大家分享到这里了,正所谓工欲善其事,必先利其器,我们掌握了诀窍,处理事情才能事倍功半,希望可以帮助到大家 。

推荐阅读