zoukankan      html  css  js  c++  java
  • 多线程学习笔记(一)线程的创建

    多线程的五种创建方式。

    第一种:通过继承Thread类

    public class CreateThread01 extends Thread{
        @Override
        public void run(){
            //在run方法中实现要实现的业务逻辑
            System.out.println(Thread.currentThread().getName());
        }
    
        public static void main(String[] args) {
            CreateThread01 thread01 = new CreateThread01();
            thread01.setName("dome1");
            thread01.start();
        }
    
    }

    第二种:通过实现 Runnable 创建线程

    public class CreateThread02 implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    
        public static void main(String[] args) {
            Thread thread = new Thread(new CreateThread02());
            thread.setName("dome2");
            thread.start();
        }
    }

    第三种:通过匿名内部类创建线程

    public class CreateThread03 {
        public static void main(String[] args) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
            thread.start();
        }
    }

    第四种:通过lambda表达式创建

    public class CreateThread04 {
        public static void main(String[] args) {
            new Thread(()-> {
                System.out.println(Thread.currentThread().getName());
            }).start();
        }
    }

    第五种:通过线程池创建

    public class CreateThread05 {
        public static void main(String[] args) {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(()->{
                System.out.println(Thread.currentThread().getName());
            });
        }
    }

    总结:其实在工作中第二种用到的比较多,在java中因为是单继承,故不推荐使用第一种,而java可以实现多个接口。所以第二种比较多。第四种为lambda表达式是java8的新特性值得深入学习

  • 相关阅读:
    vue-element-admin
    一些问题
    前端面试题(2)
    乱炖
    node与mongodb、mongoose
    NodeJs中的模块
    NodeJs基础
    论文阅读——Visual inertial odometry using coupled nonlinear optimization
    C++多线程学习之(一)——并发与多线程
    ECMAScript6的lambda(arrow function)的this绑定导致call/apply失效
  • 原文地址:https://www.cnblogs.com/huangzhimin/p/11555124.html
Copyright © 2011-2022 走看看