二.开启多线程启动的世界
1.启动线程的正确和错误方式
public static void main(String[] args) {
Runnable run = () -> System.out.println(Thread.currentThread().getName());
run.run();
sout();
Thread thread = new Thread(run);
thread.start();
}
public static void sout() {
System.out.println("sout-->" + Thread.currentThread().getName());
}
结果:
main
sout-->main
Thread-0
可以看到run和调用普通方法一样,并不涉及线程的开启
而start则开启了一个线程
2start()启动新线程
通知Jvm在有空闲的情况下,启动新线程,也就是请求Jvm来运行这个线程,而线程何时运行
由线程调度器决定,也就是在非空闲情况下,start开启一个新线程后,并不能立即启动
start被父线程调用来开启一个子线程
3子线程运行前的准备工作
首先会让自己处于就绪状态,也就是已经获得了除CPU以外的其它资源,例如
已经设置了线程上限文,栈,线程状态和pc(寄存器,指向程序运行的位置).
-------------处于就绪状态后,才能被Jvm或OS进一步调度到执行状态(等待获取CPU资源)----------
获取CPU运行资源后进入到运行状态,执行run方法里面的代码
java.lang.Thread.State
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
NEW,
/**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
RUNNABLE,
4不能重复调用start()
public static void main(String[] args) {
Thread thread = new Thread(() -> System.out.println(Thread.currentThread().getName()));
thread.start();
thread.start();
}
结果
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at com.example.threadCoreKnowledge.startThread.CantStartTwice.main(CantStartTwice.java:7)
Thread-0
源码
public synchronized void start() {
/**
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();