线程和进程

线程和进程

  • 进程:一个程序, QQ.exe Music.exe 程序的集合;
  • 一个进程往往可以包含多个线程,至少包含一个 !
  • Java默认有几个线程? 2个mian、 GC
  • 线程:开了一个进程Typora ,写字,自动保存(线程负责的)
  • 对于Java而言: Thread、Runnable、 Callable
  • Java真的可以开启线程吗?开不了

Java调用本地方法start0由底层(C++)开启

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 */
            }
        }
    }
	//本地方法
    private native void start0();

并发、并行

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

  • CPU一核,模拟出来多条线程,天下武功,唯快不破,快速交替并行(多个人-起行走)
  • CPU多核,多个线程可以同时执行;线程池
public static void main(String[] args) {
    //获取CPU的核数
    System.out.println(Runtime.getRuntime().availableProcessors());
}

并发编程的本质:充分利用CPU的资源
所有的公司都很看重!
企业,挣钱=>提高效率,裁员,找一个厉害的人顶替三个不怎么样的人;
人员(减)、技术成本(高)

线程的6种状态

image-20200802110358582

wait/sleep区别

  1. 来自不同的类

    wait=>Object

    sleep=>Thread

  2. 是否会释放锁

    wait会释放锁,sleep不会

  3. 使用范围不同

    wait必须在同步代码块中,没有锁时使用会抛出llegalMonitorStateException(正在等待的对象没有锁)

    sleep可以咋任意地方

视频参考https://www.bilibili.com/video/BV1B7411L7tE
上一篇:什么是JUC
下一篇:Lock锁

posted @ 2020-08-05 22:16  Maple_XL  阅读(140)  评论(0)    收藏  举报