多线程回顾

HeJin大约 2 分钟JavaJUC并发编程

image-20210311085423044
image-20210311085423044

Java默认线程

Java默认有2个线程:main线程和gc线程。

Java真的可以开启线程吗?不能。

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".
     */
    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 */
        }
    }
}

// 调用本地方法,底层的C++。java无法直接操作硬件。
private native void start0();

并发和并行

并发:多线程交替执行操作同一个资源。

并行:多个线程同时执行。

查看CPU核数:

public class Test1 {
    public static void main(String[] args) {
        /**
         * 获取CPU核数
         * CPU密集型,IO密集型
         */
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}

4核8线程:

8

Process finished with exit code 0

并发编程的本质:充分利用CPU的资源

线程状态

public enum State {
    // 新生
    NEW,
    // 运行
    RUNNABLE,
    // 阻塞
    BLOCKED,
    // 等待
    WAITING,
    // 超时等待
    TIMED_WAITING,
    // 终止
    TERMINATED;
}

wait和sleep区别

1、来自不同的类

wait来自Object类。sleep来自Thread类

2、锁的释放

wait会释放锁,sleep不会释放,抱着锁睡觉。

3、使用的范围是不同的

wait必须在同步方法或者同步代码块中。sleep可以在任何地方睡。

4、是否需要捕获异常

都需要。wait需要捕获异常(中断异常)。sleep需要捕获异常(中断异常)。