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);
		}
	}
}

右键执行即可。

发布了16 篇原创文章 · 获赞 69 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/xuaman/article/details/103677712