线程的4种创建方式

多线程

直接开干不废话,在java中,我们都知道创建线程一般都有两种方法,一种是通过Thread类,一种是实习Runnable接口,这两种都是我们常用的,其实还有几种也可以创建线程。下面重点介绍另外两种。

  1. 通过Thread类创建线程

        static class Thread1 extends Thread{
            @Override
            public void run() {
                System.out.println("创建线程方式一");
            }
        }
       //测试 简单的直接用lambda表达式也可以
        public static void main(String[] args) {
        //简单的直接用lambda表达式也可以
        new Thread(()-> System.out.println("线程一")).start();
            Thread1 thread1 = new Thread1();
            thread1.start(); 
        }
    
  2. 通过实现Runnable接口创建线程

        static class Thread2 implements Runnable {
            @Override
            public void run() {
                System.out.println("创新线程二");
            }
        }
     public static void main(String[] args) {     
            Thread2 thread2 = new Thread2();  
            new Thread(thread2).start();
    
        }
    
  3. Callable来创建线程

    实现过程是 Callable+ FutureTask+ Thread或许线程池来实现线程的异步任务。

    FutureTask是一个课取消的异步计算类

    首先来认识试玩一把看看该Callable是如何创建线程的。

    
        /**
         * 通过Calllable来创建线程,这个接口你补了前面两种执行完任务没有返回值的缺点,
         * 这个方法执行完任务需要返回值
         */
        static class Thread3 implements Callable<Integer> {
            @Override
            public Integer call() throws Exception {
                int sum=0;
                TimeUnit.MILLISECONDS.sleep(1000);
                for (int i=0 ; i< 100 ; i++){
                    sum+=i;
                }
                return sum;
            }
        }
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            //1.创建一个实现了Calllable的类
            Thread3 thread3 = new Thread3();
            //2.创建FutureTask 把步骤一的类(任务)丢个FutureTask去执行
            FutureTask task = new FutureTask(thread3);
            //3.把FutureTask的任务开辟一条线程去执行。
            new Thread(task,"线程三").start();
                  if (!task.isDone()){
                System.out.println("任务没完成"+task.isDone());
            }
            if (!task.isCancelled()){
                System.out.println("任务是否取消"+task.isCancelled());
            }
    
    //        if (task.cancel(true)) {
    //            System.out.println("取消任务");
    //        }
    //        if (task.isCancelled()){
    //            System.out.println("再去确认任务是否取消"+task.isCancelled());
    //        }
           //线程一new Thread(()-> System.out.println(Thread.currentThread().getName()+"线程A"),"线程A").start();
            //线程二
    new Thread(()-> System.out.println(Thread.currentThread().getName()+"线程B"),"线程B").start();
      
            System.out.println(task.get());
            System.out.println(Thread.currentThread().getName()+"任务执行完毕");
        }
    }
    控制台输出:
         	任务没完成false
            任务是否取消false
            线程A线程A
            线程B线程B
            4950
            main任务执行完毕
    

    因为FutureTask是异步计算,而且可以对任务进行取消、判断是否以及完成等操作,当任务没完成是调用get方法获取结果会进行阻塞。

  4. 通过线程池创建线程

    public class Test2 {
    //静态内部类创建单例线程池  -利用了类机制
        static class SinglePool{
      public static   ThreadPoolExecutor  executor = new ThreadPoolExecutor(4, 50, 2000, TimeUnit.SECONDS, new ArrayBlockingQueue(100));
        }
    
        /**
         * 通过Calllable来创建线程,这个接口你补了前面两种执行完任务没有返回值的缺点,
         * 这个方法执行完任务需要返回值
         */
        static class Thread3 implements Callable<Integer> {
            @Override
            public Integer call() throws Exception {
                int sum=0;
                TimeUnit.MILLISECONDS.sleep(1000);
                for (int i=0 ; i< 100 ; i++){
                    sum+=i;
                }
                return sum;
            }
        }
        public static void main(String[] args) throws ExecutionException, InterruptedException {
             Thread3 thread3 = new Thread3();
            ThreadPoolExecutor executor = SinglePool.executor;
            Future<Integer> task = executor.submit(thread3);
    
           executor.shutdown();
            System.out.println(task.get());
            System.out.println(Thread.currentThread().getName()+"任务执行完毕");
        }
    }
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值