您的位置:首页 > 其它

线程池

2016-01-17 15:21 267 查看
package com.ygl;

public class ThreadPoolRunnable implements Runnable{

@Override

public void run() {

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

System.out.println(Thread.currentThread().getName()+" is looping of "+i);

}

}

}

//*****************************************************

package com.ygl;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class ThreadPoolTest {

public static void main(String[] args) {

// ThreadPoolRunnable threadPoolRunnable=new ThreadPoolRunnable();

ExecutorService threadPool= Executors.newFixedThreadPool(3);//创建3个线程

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

//System.out.println("Task: "+i+"===============");

threadPool.execute(new ThreadPoolRunnable());

}

System.out.println("all task commit");

threadPool.shutdown();

}

}

//*************************************************************

package com.ygl;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class ThreadPoolTest {

public static void main(String[] args) {

// ThreadPoolRunnable threadPoolRunnable=new ThreadPoolRunnable();

ExecutorService threadPool= Executors.newCachedThreadPool();//根据任务动态创建线程

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

//System.out.println("Task: "+i+"===============");

threadPool.execute(new ThreadPoolRunnable());

}

System.out.println("all task commit");

threadPool.shutdown();

}

}

//************************************************************

package com.ygl;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

public class ThreadPoolTest {

public static void main(String[] args) {

// ThreadPoolRunnable threadPoolRunnable=new ThreadPoolRunnable();

ExecutorService threadPool= Executors.newCachedThreadPool();//创建3个线程

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

//System.out.println("Task: "+i+"===============");

threadPool.execute(new ThreadPoolRunnable());

}

System.out.println("all task commit");

threadPool.shutdown();

//定时任务调度

Executors.newScheduledThreadPool(3).schedule(new ThreadPoolRunnable(),10,TimeUnit.SECONDS);

Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new ThreadPoolRunnable(),10,2,TimeUnit.SECONDS);//10s后炸,每隔2s触发一次

}

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