zoukankan      html  css  js  c++  java
  • 线程基本使用--Thread内部方法调用start

    一个问题,下面的代码会如何运行

    public class TraditionalThread {
    
        public static void main(String[] args) {
            System.out.println("Main start " + Thread.currentThread().getName());
            Thread01 thread01 = new Thread01();
            thread01.tran();
        }
    }
    
    class Thread01 extends Thread{
        
        @Override
        public void run() {
            System.out.println("thread01 " + Thread.currentThread().getName());
        }
    
        public void tran() {
            start();
        }
    }
    

    经常使用线程的方式

    面对接口编程的使用,我们一般是将线程启动的操作和线程执行的任务是分开来的,将具体任务的实现使用Runnable,所以使用线程常用的是实现Runnable接口,加上目前jdk8中常用的lambda使用起来很方便

    new Thread(()->{System.out.println("Hello world")}).start()
    实现线程的两种方式,继承Thread,实现Runnable

    看看start方法的注释

    Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
    The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
    It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

    翻译的意思是,调用start()方法了,java虚拟机会调用这个线程的run方法,继续看Thread的start方法里面其实会调用一个native (java虚拟机帮我们操作) 的start0方法,通过这个方法去调用的run方法。

    最后一句的意思,扩展理解线程的生命周期,一个线程是不能启动两次的,会抛出非法操作异常

    综上,我的理解是,不管在哪里调用Thread的start方法都会启动一个线程,调用当前类的run方法。

    回到我们最开始的问题,因为在方法内部调用了start方法,表示即可启动了一个线程,所以Thread01中的run方法会执行

    结果为

    Main start main
    thread01 Thread-0
    
  • 相关阅读:
    论文阅读笔记(四)【TIP2017】:Video-Based Pedestrian Re-Identification by Adaptive Spatio-Temporal Appearance Model
    论文阅读目录
    【学习】从.txt文件读取生成编译代码。
    页面显示其他电脑图片(局域网)
    控制台爬取小说(大王饶命)
    【自学】大话设计模式控制台
    将PDF转化为wrod
    【学习】爬糗事百科,可自动翻页。
    AHP(使用于某项目设备重要度评估测试)
    【学习】类重构、通用值交换、释放内存计算时间等
  • 原文地址:https://www.cnblogs.com/wangshuyu/p/10547170.html
Copyright © 2011-2022 走看看