首页 > 编程 > Java > 正文

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

2019-11-08 18:51:21
字体:
来源:转载
供稿:网友
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 : "发射!") + ") ";}@Overridepublic void run() {// TODO Auto-generated method stubdo {try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.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(发射!) 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表