多线程基础 6 线程池

 

  • 线程池概述 * 程序启动一个新线程成本是比较高的,因为它涉及到要与操作系统进行交互。而使用线程池可以很好的提高性能,尤其是当程序中要创建大量生存期很短的线程时,更应该考虑使用线程池。线程池里的每一个线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态,等待下一个对象来使用
ExecutorService pool = Executors.newFixedThreadPool(2);//创建线程池

pool.submit(new MyRunnable());          //将线程放进池子里并执行

pool.submit(new MyRunnable());



pool.shutdown();

多线程(多线程程序实现的方式3)

 

public void print3() throws InterruptedException {

    r.lock();

    if(flag != 3) {

        c3.await();

    }



    System.out.print("hk");



    System.out.print("\r\n");

    flag = 1;

    c1.signal();

    r.unlock();



    public class Demo6_Callable {



        /**

         * @param args

         * @throws ExecutionException

         * @throws InterruptedException

         */

        public static void main(String[] args) throws InterruptedException, ExecutionException {

            ExecutorService pool = Executors.newFixedThreadPool(2);//创建线程池

            Future<Integer> f1 = pool.submit(new MyCallable(100));          //将线程放进池子里并执行

            Future<Integer> f2 = pool.submit(new MyCallable(50));



            System.out.println(f1.get());

            System.out.println(f2.get());



            pool.shutdown();                     //关闭线程池

        }



    }



    class MyCallable implements Callable<Integer> {

        private int num;

        public MyCallable(int num) {

            this.num = num;

        }

        @Override

        public Integer call() throws Exception {

            int sum = 0;

            for(int i = 1; i <= num; i++) {

                sum += i;

            }



            return sum;

        }



    }



 

线程生命周期

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值