进程与线程解析

在此之前呢,我们先对 JUC 有个简单了解:所谓 JUC 即 Java 的一个并发编程的类包:java.util.concurrent
包含有:

  • java.util.concurrent.atomic
  • java.util.concurrent.locks

进程

进程是一个程序,比如QQ、WeChat 等程序的集合

  1. 一个进程往往可以包含多个线程,至少包含1个线程。
  2. Java 默认有2个线程。mian 和 GC

线程

线程就是一个单独的资源类,没有任何附属操作~

  • 属性、方法
  1. 开启方式
    • Thread
    • Runnable
    • Callable
  2. Java真的能开启线程吗?
    • 不能,只能通过 native 去调用,底层C++,Java 无法直接操作硬件
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();
            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 */
            }
        }
    }
    

    // native 本地方法栈,调用底层C++,Java 无法直接调用硬件,所以Java无法开启线程
    private native void start0();

并发和并行

并发:多线程操作同一个资源

  • CPU 一核,模拟出来多条线程交替切换执行

并行:多个人一起行走

  • 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 必须要捕获异常
posted @ 2020-08-07 10:48  湘北不会输的  阅读(98)  评论(0)    收藏  举报