重学Java并发编程—刨根问底搞懂建立线程到底有几种方法?

Oracle官方文档对建立线程的说明

  • Java SE 8 API文档: docs.oracle.com/javase/8/do…java

    请查看java.lang.Thread的类说明文档。api

    1. 将类声明为Thread的子类,并重写run方法。

    官方原话:There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread.oracle

    /** * 实现线程的第一个方式 继承Thread * @author yiren */
    public class MyThread extends Thread {
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " Thread running...");
        }
    
        public static void main(String[] args) throws IOException {
            new MyThread().start();
            System.in.read();
        }
    }
    
    
    
    复制代码
    1. 实现Runnable接口,并实现run方法。

    官方原话:The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method.异步

/** * 实现线程的第二个方式 实现Runnable接口 * @author yiren */
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " Runnable running...");
    }

    public static void main(String[] args) throws IOException {
        new Thread(new MyRunnable()).start();
        System.in.read();
    }
}

复制代码

两种发方法的优缺点

    1. 从代码的结构上去考虑,具体线程执行的任务是run方法中的代码,至关于业务代码,它应该和咱们线程的建立解耦。
    2. 若是继承Thread,每次想建一个异步任务,咱们都须要去创建一个独立的线程。而建立一个线程的消耗是比较大的,若是是使用Runnable,咱们就能够很好得利用线程池之类的工具,这样能够大大减小建立和销毁线程的损耗。节省资源。
    3. 因为Java是单继承,继承了Thread的类事后,该类就没法再继承其余类,大大限制了可扩展性。
/* What will be run. */
    private Runnable target;

		public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }

		private void init(ThreadGroup g, Runnable target, String name, long stackSize) {
        init(g, target, name, stackSize, null, true);
    }
		
		private void init(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc, boolean inheritThreadLocals) {
        ......
        
        this.target = target;
        
      	......
    }

		@Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
复制代码
  • 两种方法的本质(由上面的Thread类的源代码可知)ide

    • 继承Thread 是整个run()方法被重写
    • 实现Runnable最终是Runnablerun方法被target.run()调用
  • 若是两种方式都用会有什么效果呢?微服务

    /** * @author yiren */
    public class MyThreadAndRunnable {
        public static void main(String[] args) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " runnable running...");
                }
            }
            ) {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " thread running...");
                }
            };
    
            // 这个地方应该是执行重写Thread类的run方法中的逻辑!
            thread.start();
        }
    }
    复制代码
    • 很明显,上面说了不重写Threadrun()方法就是调用target.run(),若是重写那也就没有调用target.run()了。
  • 准确来讲,建立线程只有一种方式,那就是构建Thread类,而实现线程的执行单元有两种方法,就是上面说的两种。工具

其余说法:

  • 线程池建立线程学习

    /** * wrong 线程池建立 * * @author yiren */
    public class ThreadPoolExample {
        public static void main(String[] args) {
            ExecutorService executorService = Executors.newCachedThreadPool();
            for (int i = 0; i < 1000; i++) {
                executorService.submit(() -> {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                });
            }
        }
    }
    
    // Executors中的DefaultThreadFactory 
    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;
            }
        }
    复制代码
    • 由上newThread()方法可知,即便是线程池,本质上仍是使用Thread的建立线程。
  • Callable和FutureTask建立线程大数据

  • 由上UML图可知,实际上内部仍是使用的Thread和Runnable来实现的。this

  • 定时器Timer

    /** * @author yiren */
    public class TimerExample {
        public static void main(String[] args) {
            Timer timer = new Timer();
            // 每隔1s打印下本身的名字
            timer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " timer running...");
                }
            }, 1000, 1000);
        }
    }
    复制代码
    • 它的TimerTask其实也是实现了Runnable接口,能够看下TimerTask这个抽象类
  • 匿名内部类、Lambda表达式 (本质也是同样的)

    /** * 匿名内部类 * @author yiren */
    public class AnonymousInnerClassExample {
        public static void main(String[] args) {
            new Thread() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            }.start();
    
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            }).start();
    
        }
    }
    
    /** * lambda表达式 * @author yiren */
    public class LambdaExample {
        public static void main(String[] args) {
            new Thread(() -> System.out.println(Thread.currentThread().getName())).start();
        }
    }
    复制代码

关于我

  • 坐标杭州,普通本科在读,计算机科学与技术专业,20年毕业。
  • 主要作Java开发,会写点Golang、Shell。对微服务、大数据比较感兴趣,预备作这个方向。
  • 目前处于菜鸟阶段,各位大佬轻喷,小弟正在疯狂学习。
  • 欢迎你们留言交流!!!
相关文章
相关标签/搜索