start()与run()启动
public class StartAndRunMethod {
public static void main(String[] args) {
Runnable runnable = () -> {
System.out.println(Thread.currentThread().getName());
};
runnable.run();
new Thread(runnable).start();
}
}
-------------------
运行结果是:
main
Thread-0
-
main
线程调用new Thread(runnable).start();
去创建Thread-0
线程,并且不是一调用start就会创建新线程,而是等待CPU
有空闲的时候采取创建新线程 -
使用
Runnable
对象调用run()
方法,就是普通的方法调用,是在main
线程里执行;而使用start()
方法启动线程才是真正启动多线程,下面是Thread
类中的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". */ //启动新线程检查线程状态是否为0 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方法 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 */ } } }
能不能start()两次?
public class CantStartTwice {
public static void main(String[] args) {
Thread thread = new Thread();
thread.start();
thread.start();
}
}
答案是不能,通过看Thread
类的start()
方法知道在创建线程是会检查线程状态threadStatus
,如果不是新的线程就会抛出异常java.lang.IllegalThreadStateException