Thread运行过程分析:

 

以下是一个最普通的Thread实现过程,我们今天就来看仔细分析下他是如何运行的。

public class ThreadRunMain {
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.setName("MyThread");
        Thread th = new Thread(mt);
        th.setName("thThread");
        th.start();
    }
}
public class MyThread extends Thread {
    public void run(){
        super.run();
        System.out.println(Thread.currentThread().getName() + " is running.");
    }
}

1. 创建MyThread的mt对象,由于是继承了Thread类,所以首先要创建Thread对象,然后创建MyThread对象。

2. 创建Thread的th对象,并且初始化target属性=mt。

Java 学习笔记之 Thread运行过程分析

3. 启动线程th。

4. 某个时刻,线程th运行,Thread类中的run方法被调用。

5. super.run()调用父类的run方法,即调用Thread类的对象的run方法,即在第一步创建的Thread对象,但由于target对象没有赋值,所以仍然为null,if语句跳出,super.run方法直接执行完毕。

Java 学习笔记之 Thread运行过程分析

6. 打印thThread is running。

7. mt.run方法执行完毕。

8. 线程th执行完毕。

 

相关文章:

  • 2022-01-05
  • 2021-07-21
  • 2022-12-23
  • 2022-12-23
  • 2021-05-17
  • 2022-12-23
  • 2021-08-08
猜你喜欢
  • 2021-04-01
  • 2021-12-06
  • 2022-01-29
  • 2022-02-28
  • 2021-06-28
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案