jdk提供的线程池_创建线程的三种方法

jdk提供的线程池_创建线程的三种方法JDK1.8创建线程池有哪几种方式?newFixedThreadPool定长线程池,每当提交一个任务就创建一个线程,直到达到线程池的最大数量,这时线程数量不再变化,当线程发生错误结束时,线程池会补充一个新的线程测试代码:publicclassTestThreadPool{ //定长线程池,每当提交一个任务就创建一个线程,直到达到线程池的最大数量,这时线程数量不再变化…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

JDK1.8 创建线程池有哪几种方式?

  • newFixedThreadPool

定长线程池,每当提交一个任务就创建一个线程,直到达到线程池的最大数量,这时线程数量不再变化,当线程发生错误结束时,线程池会补充一个新的线程

测试代码:

public class TestThreadPool {

	//定长线程池,每当提交一个任务就创建一个线程,直到达到线程池的最大数量,这时线程数量不再变化,当线程发生错误结束时,线程池会补充一个新的线程
	static ExecutorService fixedExecutor = Executors.newFixedThreadPool(3);
	
	
	public static void main(String[] args) {
		testFixedExecutor();
	}
	
	//测试定长线程池,线程池的容量为3,提交6个任务,根据打印结果可以看出先执行前3个任务,3个任务结束后再执行后面的任务
	private static void testFixedExecutor() {
		for (int i = 0; i < 6; i++) {
			final int index = i;
			fixedExecutor.execute(new Runnable() {
				public void run() {
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + " index:" + index);
				}
			});
		}
		
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("4秒后...");
		
		fixedExecutor.shutdown();
	}
	
}

打印结果:

pool-1-thread-1 index:0
pool-1-thread-2 index:1
pool-1-thread-3 index:2
4秒后...
pool-1-thread-3 index:5
pool-1-thread-1 index:3
pool-1-thread-2 index:4

 

 

  • newCachedThreadPool

可缓存的线程池,如果线程池的容量超过了任务数,自动回收空闲线程,任务增加时可以自动添加新线程,线程池的容量不限制

测试代码:  

public class TestThreadPool {

	//可缓存的线程池,如果线程池的容量超过了任务数,自动回收空闲线程,任务增加时可以自动添加新线程,线程池的容量不限制
	static ExecutorService cachedExecutor = Executors.newCachedThreadPool();
	
	
	public static void main(String[] args) {
		testCachedExecutor();
	}
	
	//测试可缓存线程池
	private static void testCachedExecutor() {
		for (int i = 0; i < 6; i++) {
			final int index = i;
			cachedExecutor.execute(new Runnable() {
				public void run() {
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + " index:" + index);
				}
			});
		}
		
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("4秒后...");
		
		cachedExecutor.shutdown();
	}
	
}

打印结果:

pool-1-thread-1 index:0
pool-1-thread-6 index:5
pool-1-thread-5 index:4
pool-1-thread-4 index:3
pool-1-thread-3 index:2
pool-1-thread-2 index:1
4秒后...

 

 

  • newScheduledThreadPool

定长线程池,可执行周期性的任务

测试代码:

public class TestThreadPool {

	//定长线程池,可执行周期性的任务
	static ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(3);
	
	
	public static void main(String[] args) {
		testScheduledExecutor();
	}
	
	//测试定长、可周期执行的线程池
	private static void testScheduledExecutor() {
		for (int i = 0; i < 3; i++) {
			final int index = i;
			//scheduleWithFixedDelay 固定的延迟时间执行任务; scheduleAtFixedRate 固定的频率执行任务
			scheduledExecutor.scheduleWithFixedDelay(new Runnable() {
				public void run() {
					System.out.println(Thread.currentThread().getName() + " index:" + index);
				}
			}, 0, 3, TimeUnit.SECONDS);
		}
		
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("4秒后...");
		
		scheduledExecutor.shutdown();
	}
	
}

打印结果:

pool-1-thread-1 index:0
pool-1-thread-2 index:1
pool-1-thread-3 index:2
pool-1-thread-1 index:0
pool-1-thread-3 index:1
pool-1-thread-1 index:2
4秒后...

 

 

  • newSingleThreadExecutor

单线程的线程池,线程异常结束,会创建一个新的线程,能确保任务按提交顺序执行

测试代码:

public class TestThreadPool {
	
	//单线程的线程池,线程异常结束,会创建一个新的线程,能确保任务按提交顺序执行
	static ExecutorService singleExecutor = Executors.newSingleThreadExecutor();
	
	
	public static void main(String[] args) {
		testSingleExecutor();
	}
	
	//测试单线程的线程池
	private static void testSingleExecutor() {
		for (int i = 0; i < 3; i++) {
			final int index = i;
			singleExecutor.execute(new Runnable() {
				public void run() {
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + " index:" + index);
				}
			});
		}
		
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("4秒后...");
		
		singleExecutor.shutdown();
	}
	
}

打印结果:

pool-1-thread-1 index:0
4秒后...
pool-1-thread-1 index:1
pool-1-thread-1 index:2

 

 

  • newSingleThreadScheduledExecutor

单线程可执行周期性任务的线程池

测试代码:

public class TestThreadPool {
	
	//单线程可执行周期性任务的线程池
	static ScheduledExecutorService singleScheduledExecutor = Executors.newSingleThreadScheduledExecutor();
	
	
	public static void main(String[] args) {
		testSingleScheduledExecutor();
	}
	
	//测试单线程可周期执行的线程池
	private static void testSingleScheduledExecutor() {
		for (int i = 0; i < 3; i++) {
			final int index = i;
			//scheduleWithFixedDelay 固定的延迟时间执行任务; scheduleAtFixedRate 固定的频率执行任务
			singleScheduledExecutor.scheduleAtFixedRate(new Runnable() {
				public void run() {
					System.out.println(Thread.currentThread().getName() + " index:" + index);
				}
			}, 0, 3, TimeUnit.SECONDS);
		}
		
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("4秒后...");
		
		singleScheduledExecutor.shutdown();
	}
	
}

打印结果:

pool-1-thread-1 index:0
pool-1-thread-1 index:1
pool-1-thread-1 index:2
pool-1-thread-1 index:0
pool-1-thread-1 index:1
pool-1-thread-1 index:2
4秒后...

 

 

  • newWorkStealingPool

任务窃取线程池,不保证执行顺序,适合任务耗时差异较大。

线程池中有多个线程队列,有的线程队列中有大量的比较耗时的任务堆积,而有的线程队列却是空的,就存在有的线程处于饥饿状态,当一个线程处于饥饿状态时,它就会去其它的线程队列中窃取任务。解决饥饿导致的效率问题。

默认创建的并行 level 是 CPU 的核数。主线程结束,即使线程池有任务也会立即停止。

测试代码:

public class TestThreadPool {

	//任务窃取线程池
	static ExecutorService workStealingExecutor = Executors.newWorkStealingPool();
	
	public static void main(String[] args) {
		testWorkStealingExecutor();
	}
	
	//测试任务窃取线程池
	private static void testWorkStealingExecutor() {
		for (int i = 0; i < 10; i++) {//本机 CPU 8核,这里创建10个任务进行测试
			final int index = i;
			workStealingExecutor.execute(new Runnable() {
				public void run() {
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + " index:" + index);
				}
			});
		}
		
		try {
			Thread.sleep(4000);//这里主线程不休眠,不会有打印输出
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("4秒后...");
		
//		workStealingExecutor.shutdown();
	}
	
}

打印结果如下,index:8,index:9并未打印出:

ForkJoinPool-1-worker-1 index:0
ForkJoinPool-1-worker-7 index:6
ForkJoinPool-1-worker-5 index:4
ForkJoinPool-1-worker-3 index:2
ForkJoinPool-1-worker-4 index:3
ForkJoinPool-1-worker-2 index:1
ForkJoinPool-1-worker-0 index:7
ForkJoinPool-1-worker-6 index:5
4秒后...

 


【Java面试题与答案】整理推荐

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/187132.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • TLSF算法分析[通俗易懂]

    TLSF算法分析[通俗易懂]注:本文的大部分内容摘录自论文《TLSF:aNewDynamicMemoryAllocatorforReal-TimeSystems》,可以通过“科学上网”访问如下链接阅读原文:http://www.gii.upv.es/tlsf/files/ecrts04_tlsf.pdf。什么是TLSFTLSF是TwoLevelSegregatedFitmemoryal

    2022年6月30日
    22
  • phpstome 激活码【注册码】

    phpstome 激活码【注册码】,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月20日
    39
  • 快速排序quicksort_快速排序的原理

    快速排序quicksort_快速排序的原理一、简介快速排序是(Quicksort)是对冒泡排序的一种改进,是非常重要且应用比较广泛的一种高效率排序算法。二、算法思路快速排序是通过多次比较和交换来实现排序,在一趟排序中把将要排序的数据分成两个独立的部分,对这两部分进行排序使得其中一部分所有数据比另一部分都要小,然后继续递归排序这两部分,最终实现所有数据有序。大致步骤如下:首先设置一个分界值也就是基准值又是也称为监视哨,通过该分界值将数据分割成两部分。将大于或等于分界值的数据集中到右边,小于分界值的数据集中到左边。一趟排序过后,左边部

    2022年8月12日
    2
  • Petalinux2019.1详细安装[通俗易懂]

    Petalinux2019.1详细安装[通俗易懂]1、首先安装虚拟机,VMware2、安装UBUNTU,ubuntu-18.04.1-desktop-amd64.iso,版本必须是这个,和petalinux-v2019.1-final-installer.run版本对应。3、安装虚拟机完成后,在windos和linux之间建立共享文件夹,使之传输文件更简单。(1)首先取得管理员权限首先输入用户密码然后设置管理员密码123456su…

    2022年9月11日
    0
  • Button.performclick()[通俗易懂]

    Button.performclick()[通俗易懂] (1)WinForm中,Button按钮有PerformClick()方法,可以模拟用户单击鼠标.即button.PerformClick()生成按钮的事件。相关网站为:http://msdn2.microsoft.com/zh-cn/library/system.windows.forms.button.performclick(VS.80).aspx(2)在一些事件处理程序中,比如Fo

    2022年6月17日
    23
  • Java(2)-Java IO输入输出流

    Java(2)-Java IO输入输出流1.什么是IOJava中I/O操作主要是指使用Java进行输入,输出操作.Java所有的I/O机制都是基于数据流进行输入输出,这些数据流表示了字符或者字节数据的流动序列。Java的I/O流提供了读写数据的标准方法。任何Java中表示数据源的对象都会提供以数据流的方式读写它的数据的方法。Java.io是大多数面向数据流的输入/输出类的主要软件

    2022年4月29日
    109

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号