码迷,mamicode.com
首页 > 编程语言 > 详细

Java newFixedThreadPool线程池实例及讲解

时间:2015-01-07 09:25:34      阅读:1418      评论:0      收藏:0      [点我收藏+]

标签:java   线程池   实例   

闲话不多说,直接上代码。

<span style="font-size:18px;">import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyThreadPool {

	private ExecutorService exe;
	private static final int POOL_SIZE = 4;
	
	public MyThreadPool() {
        exe = Executors.newFixedThreadPool(POOL_SIZE);
    }
	
	public void doTask() {
        int i = 0;
        while (i < 50) {
            exe.execute(new MyThread(i, exe));
            i++;
        }
    }
	
	class MyThread implements Runnable
    {
        int id;
        ExecutorService exe;
        MyThread(int id, ExecutorService exe) {
        	this.exe = exe;
            this.id = id;
        }
        public void run() {
        	System.out.println(id + "start");
        	try {
				Thread.sleep(5000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        	
        	System.out.println(id + "pass 5 second");
        	System.out.println("exe info:" + exe.toString());
        	try {
				Thread.sleep(5000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        	
            System.out.println(id + "end");
        }
    }
	
	public static void main(String[] args) {
        new MyThreadPool().doTask();
    }
}</span>


MyThreadPool为线程池管理类

MyThread为实际需要运行的线程类


运行log如下(一小部分):

<span style="font-size:18px;">1start
2start
3start
0start
2pass 5 second
exe info:java.util.concurrent.ThreadPoolExecutor@39890510[Running, pool size = 4, active threads = 4, queued tasks = 46, completed tasks = 0]
0pass 5 second
exe info:java.util.concurrent.ThreadPoolExecutor@39890510[Running, pool size = 4, active threads = 4, queued tasks = 46, completed tasks = 0]
3pass 5 second
exe info:java.util.concurrent.ThreadPoolExecutor@39890510[Running, pool size = 4, active threads = 4, queued tasks = 46, completed tasks = 0]
1pass 5 second
exe info:java.util.concurrent.ThreadPoolExecutor@39890510[Running, pool size = 4, active threads = 4, queued tasks = 46, completed tasks = 0]
2end
4start
0end
5start
3end
6start
1end
7start
</span>

可以看到当前在运行的线程只有前4个,队列中有46个任务在等待

只要有一个线程结束立即就会执行队列中的下一个线程


Java newFixedThreadPool线程池实例及讲解

标签:java   线程池   实例   

原文地址:http://blog.csdn.net/aqzwss/article/details/42475877

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!