二.开启多线程启动

二.开启多线程启动的世界

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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值