`

线程并发库的应用

阅读更多
/**
 * ThreadPoolTest.java
 * cn.com.songjy.test.socket.thread
 * Function: TODO 
 *
 *   version    date      author
 * ──────────────────────────────────
 *   	1.0	 2013-8-17    songjy
 *
 * Copyright (c) 2013, TNT All Rights Reserved.
 */

package cn.com.songjy.test.socket.thread;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * ClassName:ThreadPoolTest java5线程并发库的应用
 * 
 * @author songjy
 * @version 1.0
 * @since v1.0
 * @Date 2013-8-17 下午2:31:49
 */

public class ThreadPoolTest {

	private static Log log = LogFactory.getLog(ThreadPoolTest.class);

	public static void main(String[] args) {
		// ExecutorService thread_pools = Executors.newFixedThreadPool(3);// 创建固定线程池,每次只执行3个任务,其他等待
		// ExecutorService thread_pools = Executors.newCachedThreadPool();//自动创建和回收线程,来多少任务,就创建多少线程
		ExecutorService thread_pools = Executors.newSingleThreadExecutor();// 单个线程,不管来多少任务,每次只有一个线程执行任务
		for (int i = 0; i < 10; i++) {
			final int task = i;
			thread_pools.execute(new Runnable() {

				@Override
				public void run() {
					for (int i = 0; i < 10; i++) {// 每个任务循环10次
						log.info(Thread.currentThread().getName()
								+ " is looping of " + i + " task of " + task);
						try {
							Thread.sleep(20);
						} catch (InterruptedException e) {
							log.error(e.getMessage(), e);
						}
					}
				}
			});
		}

		log.info("all of 10 tasks have commited");
		thread_pools.shutdown();// 等待所有任务完毕后关闭
		// thread_pools.shutdownNow();//立即关闭

		// 线程池调度5秒后执行
		Executors.newScheduledThreadPool(3).schedule(new Runnable() {

			@Override
			public void run() {
				log.info("bombing");

			}
		}, 5, TimeUnit.SECONDS);
		
		// 线程池调度6秒后执行,且每隔2秒循环执行
		Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				log.info("bombing");

			}
		}, 6, 2, TimeUnit.SECONDS);
	}

}


java1.5线程并发库的应用

Java 并发 – 第七部分:Executors 与线程池
  • 大小: 175.5 KB
  • 大小: 211.5 KB
  • 大小: 222.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics