zoukankan      html  css  js  c++  java
  • 实现线程有哪几种方式?

    1、实现Runnable接口,重写run方法,并将该对象传入Thread对象的构造方法中。代码示例如下:

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

    2、继承Thread类,重写run方法。代码示例如下:

    public class ExtendsThread extends Thread {
    
        @Override
        public void run() {
            System.out.println("ExtendsThread run");
        }
    
        public static void main(String[] args) {
            ExtendsThread extendsThread = new ExtendsThread();
            extendsThread.start();
        }
    }

    3、线程池中由线程工厂创建线程,本质上是new Thread()创建的。jdk源码如下:

    /**
         * The default thread factory
         */
        static class DefaultThreadFactory implements ThreadFactory {
            private static final AtomicInteger poolNumber = new AtomicInteger(1);
            private final ThreadGroup group;
            private final AtomicInteger threadNumber = new AtomicInteger(1);
            private final String namePrefix;
    
            DefaultThreadFactory() {
                SecurityManager s = System.getSecurityManager();
                group = (s != null) ? s.getThreadGroup() :
                                      Thread.currentThread().getThreadGroup();
                namePrefix = "pool-" +
                              poolNumber.getAndIncrement() +
                             "-thread-";
            }
    
            public Thread newThread(Runnable r) {
                Thread t = new Thread(group, r,
                                      namePrefix + threadNumber.getAndIncrement(),
                                      0);
                if (t.isDaemon())
                    t.setDaemon(false);
                if (t.getPriority() != Thread.NORM_PRIORITY)
                    t.setPriority(Thread.NORM_PRIORITY);
                return t;
            }
        }

    4、实现Callbale<V>接口,重写call方法。代码示例如下:

    public class CallableThread implements Callable<String> {
        @Override
        public String call() throws Exception {
            return "CallableThread call";
        }
    
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            Future<String> future = executorService.submit(new CallableThread());
            String s = future.get();
            System.out.println(s);
        }
    }

    5、定时器Timer中有一个TimerThread,本质上还是通过继承Thread创建线程的。jdk源码如下:

    public class Timer {
    
        /**
         * The timer thread.
         */
        private final TimerThread thread = new TimerThread(queue);
    
        // 省略了一些代码 
    class TimerThread extends Thread {
        // 省略了一些代码  
    }

    6、匿名内部类或lambda创建线程,代码示例如下:

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        }).start();
    }
    public static void main(String[] args) {
        new Thread(() -> System.out.println(Thread.currentThread().getName())).start();
    }
  • 相关阅读:
    Java内部类
    sql几种连接的区别
    常见的十大算法
    使用yml文件配置数据库数据时的问题
    SpringBoot整合Mybatis
    不是书评 :《我是一只IT小小鸟》
    考试考完了·
    MSSQL站库分离情况的渗透思路
    VENOM cve-2015-3456 Qemu 虚拟机逃逸漏洞POC
    Python 实现指定目录下 删除指定大小的文件
  • 原文地址:https://www.cnblogs.com/mgyboom/p/13586711.html
Copyright © 2011-2022 走看看