JAVA线程池的基本使用-ThreadPoolExecutor

最近在搞文件分片传输,无意间接触到了线程池,网上很多资料写的都太复杂了,不适合新手使用,下面咱们介绍一下线程池的基本用法。

第一步:new一个线程池。

ThreadPoolExecutor moThrPool = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<Runnable>());

注:只需要关注第一个参数,线程池大小(容量)就行了,别的自行研究/

第二步:创建线程类,即需要执行的线程。我用的内部类,也可以是普通类。

	private static class runNum implements Runnable {
		private int thisNum;

		public runNum(int num) {
			thisNum = num;
		}

		@Override
		public void run() {
			System.out.println(Thread.currentThread() +":"+ thisNum);
		}
	}

注:必须继承Runnable接口,否则跑不起来。因为线程的执行是通过调用接口方法来实现的(原因自行研究)。

第三步:线程池执行线程。

moThrPool.execute(new runNum(1));

综合可执行代码:


import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Runtest {

	public static void main(String[] args) throws InterruptedException {
		ThreadPoolExecutor moThrPool = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<Runnable>());
		for (int i = 0; i < 20; i++) {
			moThrPool.execute(new runNum(i));
		}
		Thread.sleep(5000);
		System.out.println(moThrPool.isShutdown());
		moThrPool.shutdown();
		System.out.println(moThrPool.isShutdown());
	}

	private static class runNum implements Runnable {
		private int thisNum;

		public runNum(int num) {
			thisNum = num;
		}

		@Override
		public void run() {
			System.out.println(Thread.currentThread() + ":" + thisNum);
		}
	}
}

右键执行即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值