多线程-线程启动
2021-04-15 本文已影响0人
余生爱静
线程的启动很简单,创建好线程以后,直接调用线程的start()即可。那我们从源码看下start()方法:
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
1、start方法加了synchronized
2、最后调用本地的start0()方法
private native void start0();
最终线程的启动还是调用native方法实现的。
问题一、直接调用线程的run方法
@Override
public void run() {
if (target != null) {
target.run();
}
}
1、对于继承自Thread类调用线程的run方法:
public class ThreadExtents extends Thread{
@Override
public void run() {
System.out.println("This is thread extents"+Thread.currentThread());
}
}
ThreadExtents threadExtents=new ThreadExtents();
threadExtents.run();
image.png
2、对于实现Runnable调用run方法
public class ThreadImplRunnable implements Runnable{
@Override
public void run() {
System.out.println("This is thread implements:"+Thread.currentThread());
}
}
ThreadImplRunnable runnable=new ThreadImplRunnable();
Thread thread=new Thread(runnable);
thread.run();
image.png
结论:如果直接调用Thread的run方法的话,不会启动线程,只是调用了Thread类的run方法而已,此时Thread只是一个普通的类。
问题二、如果既继承了Thread类,还实现了Runnable,那run方法结果如何?
Thread thread1=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("This is call runnable`s run method");
}
}){
@Override
public void run() {
System.out.println("This is override Thread`s run method");
}
};
thread1.start();
image.png
结论:如果一个线程既继承了Thread类,同样实现了Runnable接口,则最后调用的Thread类的重写run方法。