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();
    }
  • 相关阅读:
    获取文件夹下的所有文件名,并修改某些文件名 Alec
    生成XML文件,并保存到本地文件 Alec
    按Enter键起到Tab键的效果 Alec
    网站底部浮动js Alec
    NET Framework4.0注册 Alec
    从FTP上下载文件到本地 Alec
    生成txt日志操作文件 Alec
    不使用第三个变量,实现两个变量值的交换 Alec
    生成指定位数的回文素数 Alec
    单击gridview某一列弹出详细信息 Alec
  • 原文地址:https://www.cnblogs.com/mgyboom/p/13586711.html
Copyright © 2011-2022 走看看