首页 > 其他 > 详细

线程池helloworld

时间:2014-02-25 14:59:14      阅读:351      评论:0      收藏:0      [点我收藏+]

用线程池替代Thread,可对线程的创建、销毁、运行进行管理。

1.Runnable

package executor;

public class LiftOff implements Runnable {
	
	protected int countDown = 10;
	private static int taskCount = 0;
	private final int id = taskCount++;
	private static int count = 0;
	
	public LiftOff() {
		super();
	}
	
	public LiftOff(int countDown) {
		this.countDown = countDown;
	}
	
	public String status() {
		return "#" + id + "(" + (countDown>0 ? countDown : "LiftOff") + "), ";
	}
	
	@Override
	public void run() {
		while(countDown-- > 0) {
			if(++count >= 8) {
				System.out.println(status());
				count = 0;
			} else {
				System.out.print(status());
			}
			Thread.yield();
		}
	}

}
2. 不同的Runnable调用方法

package executor;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.junit.Test;

public class ExecutorTest {
	
	@Test
	public void testThread() {
		for(int i=0; i<5; i++) {
			new Thread(new LiftOff()).start();
		} 
		System.out.print("wating for LiftOff...");
	}
	
	//在线程数量不够时,动态创建线程
	@Test
	public void testCacheThreadExcutor() {
		Executor exec = Executors.newCachedThreadPool();
		for(int i=0; i<5; i++) {
			exec.execute(new LiftOff());
		} 
		System.out.print("wating for LiftOff...");
	}
	
	//固定数量线程池,减少线程创建的开销,
	@Test
	public void testFixThreadExcutor() {
		Executor exec = Executors.newFixedThreadPool(5);
		for(int i=0; i<5; i++) {
			exec.execute(new LiftOff());
		} 
		System.out.print("wating for LiftOff...");
	}
	
	//线程数量为1,多个任务排队执行
	@Test
	public void testSingleThreadExcutor() {
		Executor exec = Executors.newSingleThreadExecutor();
		for(int i=0; i<5; i++) {
			exec.execute(new LiftOff());
		} 
		System.out.print("wating for LiftOff...");
	}
	
}



线程池helloworld

原文:http://blog.csdn.net/y172158950/article/details/19828835

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!