欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDK1.5 线程池

程序员文章站 2022-05-28 18:24:45
...

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

/**
 * java 线程池  和 带定时器的线程池 
 */
public class ThreadPoolTest {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//固定大小的线程池
		//ExecutorService threadPool= Executors.newFixedThreadPool(3);
		//缓存的线程池  池子里面线程 会动态变化
		//ExecutorService threadPool= Executors.newFixedThreadPool(3);
		//单一线程池 .  如何实现 线程死了后,再重新启动.
		ExecutorService threadPool= Executors.newSingleThreadExecutor();
		for (int i = 0; i < 10; i++) {
			final int task=i;
			threadPool.execute(new Runnable(){
				@Override
				public void run() {
					// TODO Auto-generated method stub
					for (int j = 0; j < 10; j++) {
						System.out.println(Thread.currentThread().getName()+" is loop of"+j+" for task of"+task);
					}
				}
			});
		}
		System.out.println(" all of 10 task have committed!");
		//threadPool.shutdown(); // 把任务执行完后就,线程池子就关闭
		//threadPool.shutdownNow(); //不管提交的任务是否执行完, 现在必须关闭
		
		//带定时器的 线程池 
		Executors.newScheduledThreadPool(3).schedule(
				new Runnable() {
					@Override
					public void run() {
						System.out.println("bombing!");
					}
				}, 
				10, 
				TimeUnit.SECONDS);
		
		//固定频率执行某一个任务
		Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
				new Runnable() {
					@Override
					public void run() {
						System.out.println("bombing2!");
					}
				}, 
				10,
				2,
				TimeUnit.SECONDS);
		
		//延迟提交任务
		Executors.newScheduledThreadPool(3).scheduleWithFixedDelay(
				new Runnable() {
					@Override
					public void run() {
						System.out.println("bombing3!");
					}
				}, 
				10,
				2,
				TimeUnit.SECONDS);
		
	}

}
相关标签: 线程池