[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[整理]Java的ExecutorService简单范例理解~~

上一篇:[整理]在网页中HTML内嵌 Vcastr 播放器,播放FLV~~
下一篇:[备忘]mysql有索引,不走索引的一个小问题~~

添加日期:2013/8/27 14:58:38 快速返回   返回列表 阅读7232次
直接上程序:


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class Executor {

    private static final ExecutorService exec = Executors.newFixedThreadPool(3);
    
    /**
     * @param args
     */
    public static void main(String[] args) {

        for(int i=1;i<=5;i++){
            exec.execute(new myThread(i));
        }
    }

}

class myThread extends Thread{
    int count = 0;
    myThread(int i){
        count = i;
    }
    public void run() {
        System.out.println("----thread " + count + " start----");
        
        //sleep随机秒
        try {
            Thread.sleep(1+(int)(Math.random()*5));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("----thread " + count + " end----");
    }
}



执行结果:
----thread 1 start----
----thread 3 start----
----thread 2 start----
----thread 3 end----
----thread 4 start----
----thread 2 end----
----thread 5 start----
----thread 5 end----
----thread 1 end----
----thread 4 end----

说明:
Executors.newFixedThreadPool(3),是创建固定大小是3的线程池,
最多同时处理3个任务,更多的任务需要等待,直到有线程可用~~
线程池固定大小,不会变大,不会变小~~

(2)
如果换成Executors.newCachedThreadPool(),则创建动态大小的线程池,
任务多时,自动创建新线程,任务完毕,线程就呗咔嚓掉~~
线程池的大小,无限制~~

结果是:
----thread 1 start----
----thread 4 start----
----thread 2 start----
----thread 3 start----
----thread 5 start----
----thread 1 end----
----thread 2 end----
----thread 4 end----
----thread 5 end----
----thread 3 end----
任务同时开始了~~

(3)
如果换成Executors.newSingleThreadExecutor(),即单线程的执行器~~
结果是
----thread 1 start----
----thread 1 end----
----thread 2 start----
----thread 2 end----
----thread 3 start----
----thread 3 end----
----thread 4 start----
----thread 4 end----
----thread 5 start----
----thread 5 end----
即任务依次执行。

 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved