线程的几种创建方式

创建线程的4钟方式
* 1.继承Thread类
* 2.实现Runnable 接口
* 3.实现Callable 接口 + futureTask (可以拿到返回结果,可以处理异常)
* 4.线程池

1.继承Thread类

public class ThreadTest01 {

    //继承Thread类
    public static class Thread01 extends Thread{
        @Override
        public void run() {
            System.out.println("当前线程 -> "+Thread.currentThread().getId());

            //模拟业务执行
            int i = 10/2;

            System.out.println("运行结果 -> "+i);
        }
    }

    public static void main(String[] args) {
        System.out.println("main ...  start...");
            
        Thread01 thread01 = new Thread01();
        thread01.start(); //执行异步

        System.out.println("main ...  end...");

    }
}

结果

 

2.实现Runnable 接口

public class ThreadTest01 {

    //实现Runnable
    public static class Runnable01 implements Runnable{
        @Override
        public void run() {
            System.out.println("当前线程 -> "+Thread.currentThread().getId());

            //模拟业务执行
            int i = 10/2;

            System.out.println("运行结果 -> "+i);
        }
    }

    public static void main(String[] args) {
        System.out.println("main ...  start...");

        Runnable01 runnable01 = new Runnable01();
        new Thread(runnable01).start();//开启异步执行

        System.out.println("main ...  end...");
    }
}

结果

3.实现Callable 接口 + futureTask

public class ThreadTest01 {

    //实现Callable接口
    public static class Callable01 implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程 -> "+Thread.currentThread().getId());

            //模拟业务执行
            int i = 10/2;
            System.out.println("运行结果 -> "+i);

            //返回结果
            return i;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main ...  start...");

        FutureTask task = new FutureTask<>(new Callable01());
        new Thread(task).start(); //开启异步执行

        //等待线程执行完成 获取返回结果  阻塞等待
        Integer o = (Integer) task.get();
        System.out.println("返回结果 -> "+o);

        System.out.println("main ...  end...");
    }
}

 结果

 4.线程池 创建线程池的方式

  
/**
 * 创建线程池的方式  
 * Executors.newCachedThreadPool(); code是0 所有都可回收
 * Executors.newFixedThreadPool();  固定大小 code = max; 都不可回收
 * Executors.newScheduledThreadPool(); 定时任务的线程池
 * Executors.newSingleThreadExecutor(); 单线程的线程池,后台从队列获取任务 挨个执行
 */ 

1.Executors.newFixedThreadPool(10);



/**
* 七大参数
* int corePoolSize,  核心线程数  线程池创建好以后就准备就绪的线程数量 就等待来接收异步任务去执行
* int maximumPoolSize, 最大线程数量 控制资源并发
* long keepAliveTime, 存活时间 如果当前线程大于核心线程数量  释放空闲线程(maximumPoolSize-corePoolSize)  只要线程空闲大于指定的keepAliveTime
* TimeUnit unit, 时间单位
* BlockingQueue<Runnable> workQueue, 阻塞队列 如果任务有很多就会将目前多的任务放在队列里面 只要有线程空闲了 就会从队列里面取出新的任务继续执行
* ThreadFactory threadFactory, 线程的创建工厂
* RejectedExecutionHandler handler 如果队列满了 按照我们指定的拒绝策略拒绝执行任务
*
* 工作顺序
*  1.线程池创建,准备好core数量的核心线程,准备好接受任务
*  2.core满了,就将再进来的任务放入阻塞队列中,空闲的core就会自己去阻塞队列获取任务执行
*  3.阻塞队列满了,就直接开新线程执行,最大只能开到max指定的数量
*  4.max 满了就用RejectedExecutionHandler拒绝任务
*  5.max 都执行完成,又很多空闲。在指定的时间keepAliveTime以后 释放max- core 这些线程
*  6.new linkedBlockingDeque<>():默认是Integer 的最大值  内存不够问题
*  7.  一个线程池 core 7 ; max 20 queue 50  ,100并发进来怎末分配的
*    7个会立即得到执行,50个会进入队列, 再开13个进行执行, 剩下的30个就使用拒绝策略
*    如果不想抛弃 还要执行 callerRunsPolicy
*/
2.ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                200,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
  );
5.线程池 采用Executors 工具类
public class ThreadTest01 {
    /**
     * 创建线程池 当前系统中 线程池只有一两个  每个异步任务都提交给线程池去执行 控制资源
     * Executors.newCachedThreadPool(); code是0 所有都可回收
     * Executors.newFixedThreadPool();  固定大小 code = max; 都不可回收
     * Executors.newScheduledThreadPool(); 定时任务的线程池
     * Executors.newSingleThreadExecutor(); 单线程的线程池,后台从队列获取任务 挨个执行
     */
    public static ExecutorService executorService = Executors.newFixedThreadPool(10);

    //实现Runnable接口
    public static class Runnable01 implements Runnable{

        @Override
        public void run() {
            System.out.println("当前线程 -> "+Thread.currentThread().getId());

            //模拟业务执行
            int i = 10/2;

            System.out.println("运行结果 -> "+i);
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main ...  start...");

        //传入一个Runnable
        executorService.execute(new Runnable01());

        System.out.println("main ...  end...");
    }
}

结果

 5.线程池 采用原生

public class ThreadTest01 {

    //实现Runnable接口
    public static class Runnable01 implements Runnable{

        @Override
        public void run() {
            System.out.println("当前线程 -> "+Thread.currentThread().getId());

            //模拟业务执行
            int i = 10/2;

            System.out.println("运行结果 -> "+i);
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main ...  start...");

        //传入一个Runnable
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                200,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        executor.execute(new Runnable01());
        System.out.println("main ...  end...");
    }
}

结果

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值