您的位置:首页 > 编程语言

多线程编程6-----Executors的使用

2014-09-01 16:00 120 查看
package zhu.ThreadPools;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

public class Demo1 {

public static void main(String[] args) {

//huoqu 线程池 且指定线程

ExecutorService threadPool0= Executors.newFixedThreadPool(3);//固定3个线程

// ExecutorService threadPool1= Executors.newCachedThreadPool();//自动增减线程

ExecutorService threadPool2= Executors.newSingleThreadExecutor();//线程池只有一个线程 单线程 可以保证单线程死了之后重新建立单个线程

for(int i=1;i<11;i++){

final int task = i;

//每次只有三个线程交替执行

threadPool0.execute(

new Runnable()

{

public void run()

{

for(int i=1;i<11;i++)

{

try {

Thread.sleep(20);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName()+"is loop"+i+","+task);}

}

});

}

System.out.println("10 task have commited");

// threadPool.shutdownNow();//立即关闭线程池

//定时线程执行

Executors.newScheduledThreadPool(3)

.schedule

(new Runnable() {

@Override

public void run() {

System.out.println("boom!!!!");

}

}, 4, TimeUnit.SECONDS);

//定时线程执行2 固定的平率

Executors.newScheduledThreadPool(3)

.scheduleWithFixedDelay(new Runnable() {

@Override

public void run() {

System.out.println("bb");

}

}, 6, //多少时间开始 相对时间, 解决定时 开始时间-当前时间

2, //每隔多少秒执行一次

TimeUnit.SECONDS);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: