Executor框架与Java线程池

Executor框架

Executor基于生产者-消费者模式,提交任务的操作相当于生产者(生成待完成的工作单元),执行任务的线程则相当于消费者(执行完这些工作单元)。它提供了一种标准的方法将任务的提交和过程与执行过程解耦开来。

几种线程池(ExecutorService)

newFixedThreadPool-固定长度线程池,每提交一个任务创建一个线程。

示例代码:

public class FixedThreadPoolTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            executorService.submit(new MyRunnable((i + 1) * 5));
        }
        executorService.shutdown();
    }

    private static class MyRunnable implements Runnable {
        private int sleepSec;

        public MyRunnable(int sleepSec) {
            this.sleepSec = sleepSec;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " will run for " + sleepSec + "s");
            try {
                SECONDS.sleep(sleepSec);
                System.out.println(Thread.currentThread().getName() + " is done!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

newCachedThreadPool-可缓存线程池,线程池规模不受限制。

示例代码:

public class CachedThreadPoolTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.submit(new MyRunnable((i + 1) * 5));
        }
        executorService.shutdown();
    }

    private static class MyRunnable implements Runnable {
        private int sleepSec;

        public MyRunnable(int sleepSec) {
            this.sleepSec = sleepSec;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " will run for " + sleepSec + "s");
            try {
                SECONDS.sleep(sleepSec);
                System.out.println(Thread.currentThread().getName() + " is done!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

newSingleThreadExecutor-单线程Executor,创建单个工作者线程来执行任务。

示例代码:

public class SingleThreadPoolTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            executorService.submit(new MyRunnable((i + 1) * 5));
        }
        executorService.shutdown();
    }

    private static class MyRunnable implements Runnable {
        private int sleepSec;

        public MyRunnable(int sleepSec) {
            this.sleepSec = sleepSec;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " will run for " + sleepSec + "s");
            try {
                SECONDS.sleep(sleepSec);
                System.out.println(Thread.currentThread().getName() + " is done!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

newScheduledThreadPool-固定长度线程池,且以延迟或定时的方式来执行任务,类似Timer。

示例代码:Timer与ScheduledExecutorService比较

public class OutofTime {
    public static void main(String[] args) throws InterruptedException {
        Timer timer = new Timer();
        timer.schedule(new ThrowTask(), 1);
        SECONDS.sleep(1);
        timer.schedule(new ThrowTask(), 5);
        SECONDS.sleep(5);
    }

    static class ThrowTask extends TimerTask {

        @Override
        public void run() {
            System.out.println("Ah...");
            throw new RuntimeException();
        }
    }
}
public class InTime {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
        executor.schedule(new ThrowTask(), 1, TimeUnit.SECONDS);
        SECONDS.sleep(1);
        executor.schedule(new ThrowTask(), 5, TimeUnit.SECONDS);
        SECONDS.sleep(5);
        executor.shutdown();
    }

    static class ThrowTask implements Runnable {

        @Override
        public void run() {
            System.out.println("Ah....");
            throw new RuntimeException();
        }
    }
}

参考:《Java并发编程实战》

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值