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。
3. 启动线程th。
4. 某个时刻,线程th运行,Thread类中的run方法被调用。
5. super.run()调用父类的run方法,即调用Thread类的对象的run方法,即在第一步创建的Thread对象,但由于target对象没有赋值,所以仍然为null,if语句跳出,super.run方法直接执行完毕。
6. 打印thThread is running。
7. mt.run方法执行完毕。
8. 线程th执行完毕。