java线程池的几种写法

  第 1 种写法:可缓存线程池

	/**
	 * 第1种写法 2022-10-17 newCachedThreadPool 创建一个可缓存线程池
	 * https://blog.csdn.net/chaochao2113/article/details/118861041
	 */
	private static void pool_1() {
		ExecutorService excuPool = Executors.newCachedThreadPool();
		for (int a = 0; a < 5; a++) {
			System.out.println("这是里面的a的值=" + a);
			excuPool.execute(new Runnable() {
				public void run() {
					// 业务逻辑方法
					show1();
					System.out.println("业务逻辑1---" + Thread.currentThread().getName() + "它的getID="
							+ Thread.currentThread().getId());

				}
			});
		}
		excuPool.shutdown();
	}

运行

	public static void main(String[] args) {

		/**
		 * 可缓存线程池
		 */
		pool_1();
	}

输出结果

第2种写法,指定线程池大小

	/**
	 * 第2种线程池的写法,指定线程池的个数
	 * https://blog.csdn.net/qq_21438267/article/details/120241770 2022-10-13
	 */
	public static void pool_2() {
		ExecutorService executorService2 = Executors.newFixedThreadPool(5);
		for (int i = 0; i < 10000; i++) {
			System.out.println("开始运行:=" + i);
			Runnable runb = new Runnable() {
				public void run() {
					// 里面写业务逻辑
					System.out.println("业务逻辑2---" + Thread.currentThread().getName() + "它的getID="
							+ Thread.currentThread().getId());
				}
			};
			executorService2.execute(runb);

		}
		// 关闭线程池
		executorService2.shutdown();

	}

第3种,延时3秒,执行

	/**
	 * 2022-10-17 支持定时及周期性任务执行,延迟3秒执行
	 */
	public static void pool_3() {
		System.out.println("开始处理poo3方法中的逻辑");
		ScheduledExecutorService schdpool = Executors.newScheduledThreadPool(5);
		schdpool.schedule(new Runnable() {
			public void run() {
				// 处理业务逻辑
				for (int b = 0; b < 2000; b++) {
					System.out.println(b);
					show1();
					System.out.println("业务逻辑3---" + Thread.currentThread().getName() + "它的getID="
							+ Thread.currentThread().getId());
				}

			}
		}, 3, TimeUnit.SECONDS);
		schdpool.shutdown();
	}

第4种写法,定时,延时执行

	/**
	 * 表示延迟1秒后每3秒执行一次。
	 * 2022-10-17
	 */
	public static void pool_4() {
		ScheduledExecutorService schdupoo4=Executors.newScheduledThreadPool(3);
		schdupoo4.scheduleAtFixedRate(new Runnable() {
			public void run() {
				for (int b = 0; b < 200000; b++) {
					System.out.println(b);
					show1();
					System.out.println("业务逻辑4---" + Thread.currentThread().getName() + "它的getID="
							+ Thread.currentThread().getId());
				}
			}
		}, 1, 3, TimeUnit.SECONDS); // 表示延迟1秒后每3秒执行一次。
		schdupoo4.shutdown();
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值