一个问题,下面的代码会如何运行
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