Java实例 改进发射小程序 java.util.concurrent.Executor执行器来处理多任务多线程

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


class LiftOff implements Runnable {
protected int countDown = 10;  //默认值
private static int taskCount = 0 ;
private final int id = taskCount++;

public LiftOff(int countDown) {
this.countDown = countDown;
}


public LiftOff() {
// TODO Auto-generated constructor stub
}


public String status() {
return "#" + id + "(" + (countDown >0 ? countDown : "发射!") + ") ";
}



@Override
public void run() {
// TODO Auto-generated method stub
do {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(status());
Thread.yield();
} while (countDown-- >0) ;
}


}


public class Test05 {
public static void main(String[] args) {
ExecutorService t = Executors. newCachedThreadPool();

for (int i = 1; i < 5; i++) {
t.execute(new LiftOff());
System.out.println("倒计时十秒,火箭"+i+"等待发射!");
}
t.shutdown();

}


}

运行结果:

倒计时十秒,火箭1等待发射!
倒计时十秒,火箭2等待发射!
倒计时十秒,火箭3等待发射!
倒计时十秒,火箭4等待发射!
#0(10) 
#2(10) 
#3(10) 
#1(10) 
#0(9) 
#1(9) 
#3(9) 
#2(9) 
#0(8) 
#2(8) 
#3(8) 
#1(8) 
#0(7) 
#2(7) 
#3(7) 
#1(7) 
#0(6) 
#1(6) 
#2(6) 
#3(6) 
#0(5) 
#3(5) 
#2(5) 
#1(5) 
#0(4) 
#2(4) 
#3(4) 
#1(4) 
#0(3) 
#1(3) 
#2(3) 
#3(3) 
#0(2) 
#3(2) 
#2(2) 
#1(2) 
#0(1) 
#1(1) 
#2(1) 
#3(1) 
#0(发射!) 
#1(发射!) 
#2(发射!) 
#3(发射!) 


newCachedThreadPool 将为每个任务都创建一个线程!

shutdown()方法可以防止新任务被提交给这个Executor,这个要放在execute()方法提交所有任务之后


newCachedThreadPool 替换为newFixedThreadPool

newFixedThreadPool使用了有限的线程集来执行所提交的任务


ExecutorService t = Executors.newFixedThreadPool(4);

4个线程:

如果是0 报错

如果是1 只能按照顺序一个一个来

如果是2 两个两个一起来

如果是3 先执行3个,最后一个第二批执行

如果是4 全部执行


newSingleThreadExecutor就像是数量为1的newFixedThreadPool

ExecutorService t = Executors.newSingleThreadExecutor();

只能按照顺序一个一个来


运行结果:

倒计时十秒,火箭1等待发射!
倒计时十秒,火箭2等待发射!
倒计时十秒,火箭3等待发射!
倒计时十秒,火箭4等待发射!
#0(10) 
#0(9) 
#0(8) 
#0(7) 
#0(6) 
#0(5) 
#0(4) 
#0(3) 
#0(2) 
#0(1) 
#0(发射!) 
#1(10) 
#1(9) 
#1(8) 
#1(7) 
#1(6) 
#1(5) 
#1(4) 
#1(3) 
#1(2) 
#1(1) 
#1(发射!) 
#2(10) 
#2(9) 
#2(8) 
#2(7) 
#2(6) 
#2(5) 
#2(4) 
#2(3) 
#2(2) 
#2(1) 
#2(发射!) 
#3(10) 
#3(9) 
#3(8) 
#3(7) 
#3(6) 
#3(5) 
#3(4) 
#3(3) 
#3(2) 
#3(1) 
#3(发射!) 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值