初识 Java 线程池

初识 Java 线程池

正常情况下我们使用线程都是用new Thread().这里给大家说一下它的弊端以及Java四种线程池的使用.

new Thread()的弊端

执行一个异步任务你还只是如下new Thread()吗?

        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
            }
        }).start();

那你就out太多了,new Thread()的弊端如下:
a. 每次new Thread()都会新建对象导致性能差。
b. 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。
c. 缺乏更多功能,如定时执行、定期执行、线程中断。
相比new Thread(),Java提供的四种线程池的好处在于:
a. 重用存在的线程,减少对象创建、消亡的开销,性能更佳。
b. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。
c. 提供定时执行、定期执行、单线程、并发数控制等功能。

首先我们来看看Thread 的用法

public class ThreadTest {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            final int index = i;
            try {
                Thread.sleep(index * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            new Thread(new Runnable() {

                public void run() {
                    System.out.println(Thread.currentThread().getId() + "");
                }

            }).start();;
        }
    }

}

//输出结果
11
12
13
14
15
16
17
18
19
20

可以看出创建了10个不同的线程

Java 线程池

Java通过Executors提供四种线程池,分别为:
1. newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
2. newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
3. newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
4. newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

下面我们一个一个来分析:

1. newCachedThreadPool

创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例代码如下:

public class CachedTheardPoolTest {

    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            cachedThreadPool.execute(new Runnable() {

                public void run() {
                    System.out.println(Thread.currentThread().getId() + "");
                }
            });
        }
    }

}

//输出结果
11
11
11
11
11
11
11
11
11
11

线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。

2. newFixedThreadPool

创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:

public class FixedThreadPoolTest {

    public static void main(String[] args) {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int index = i;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            fixedThreadPool.execute(new Runnable() {

                public void run() {
                    System.out.println(Thread.currentThread().getId() + "");
                }
            });
        }

    }

}

//输出结果
11
12
13
11
12
13
11
12
13
11

因为线程池大小为3,所以只创建三个可用线程,超出的等待之前任务完成后才执行.
定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()。

3. newScheduledThreadPool

创建一个定长线程池,支持定时及周期性任务执行。延迟执行示例代码如下:

public class ScheduledThreadPoolTest {

    public static void main(String[] args) {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
        //延迟三秒执行
        scheduledThreadPool.schedule(new Runnable() {

            public void run() {
                System.out.println("delay 3 seconds");
            }
        }, 3, TimeUnit.SECONDS);

        //延迟1秒后每3秒执行一次
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {

            public void run() {
                System.out.println("delay 1 seconds, and excute every 3 seconds");
            }
        }, 1, 3, TimeUnit.SECONDS);
    }

}


//输出结果
delay 1 seconds, and excute every 3 seconds
11
delay 3 seconds
12
delay 1 seconds, and excute every 3 seconds
11
delay 1 seconds, and excute every 3 seconds
11
delay 1 seconds, and excute every 3 seconds
11
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
12
delay 1 seconds, and excute every 3 seconds
12
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
14

ScheduledExecutorService比Timer更安全,功能更强大.

4. newSingleThreadExecutor

创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下:

public class SingleThreadExecutorTest {

    public static void main(String[] args) {

        ExecutorService singleThreadExecutor = Executors
                .newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            singleThreadExecutor.execute(new Runnable() {
                public void run() {
                    System.out.println(Thread.currentThread().getId() + "");
                }
            });
        }
    }

}


//输出结果
11
11
11
11
11
11
11
11
11
11

结果依次输出,相当于顺序执行各个任务。
现行大多数GUI程序都是单线程的。适用于IO操作,不阻塞主线程.

Demo下载

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值