JUC入门

JUC入门

1、什么是JUC

  • java.util工具包

java.util.concurrent

java.util.concurrent.atomic

java.util.concurrentLocks

  • Runnable没有返回值--效率相对于Callable低!

2、线程和进程

进程、线程

进程:一个程序 qq.exe Music.exe

一个进程往往可以包含多个线程,至少一个!

java默认有几个线程?两个!一个main线程,一个GC线程

线程:开了一个进程Typora,写字,自动保存(线程负责的) Thread Runnabe Callable

java真的可以开启线程吗? 不可以!!

new 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一核 模拟出来多条线程,天下武功,为快不破,快速交替

并行:多个人一起行走

  • CPU多核,多个线程可以执行
package juc;

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

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

线程有几个状态 6个

  • NEW //新生
  • RUNNABLE//运行
  • BLOCKED//阻塞
  • WAITING//等待【死死的等】
  • TIMED_WAITING//超时等待【有等待截止时间】
  • TIMEINATED//截止

wait/sleep区别

  • 来自不同的类 wait----》Object sleep-----》Thread【企业当中不用sleep】

    import java.util.concurrent.TimeUnit;//juc包下的
    //一般会用这类
    TimeUnit.SECONDS.sleep(2);//睡两秒
    TimeUnit.DAYS.sleep(1);//睡一天
    
  • 关于锁的释放

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

  • 使用范围不同

    wait:必须在同步代码块中【需要等人哦hhh】

    sleep:可以在任何地睡觉

  • 是否需要捕获异常

    wait:方法不需要捕获异常

    sleep:会有异常

3、Lock锁(重点)

传统synchronized

posted @ 2020-12-19 01:11  学点东西真不容易  阅读(126)  评论(0编辑  收藏  举报