线程池helloworld

用线程池替代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...");
	}
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值