赞
踩
视频链接:参考【狂神说Java】JUC并发编程最新版通俗易懂
JUC 就是 java.util.concurrent 下面的类包,专门用于多线程的开发。
线程是进程中的一个实体,线程本身是不会独立存在的。
进程是代码在数据集合上的一次运行活动, 是系统进行资源分配和调度的基本单位。
线程则是进程的一个执行路径, 一个进程中至少有一个线程,进程中的多个线程共享进程的资源。
操作系统在分配资源时是把资源分配给进程的, 但是CPU 资源比较特殊, 它是被分配到线程的, 因为真正要占用C PU 运行的是线程, 所以也说线程是CPU 分配的基本单位。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UDB6nUOZ-1606918113424)(C:\Users\10511\AppData\Roaming\Typora\typora-user-images\1606133719007.png)]
Java 默认有 2 线程 !(mian 线程、GC 线程)
Java 中,使用 Thread、Runnable、Callable 开启线程。
Java 没有权限开启线程 、Thread.start() 方法调用了一个 native 方法 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 */ } } } // Java 没有权限操作底层硬件的 private native void start0();
并发是指同一个时间段内多个任务同时都在执行,并都没有执行结束。
并行是说在单位时间内多个任务同时在执行。
在单 CPU 时代,多个任务都是并发执行的,这是因为单个 CPU 同时只能执行一个任务。
多个 CPU 意味着每个线程可以使用自己的 CPU 运行,这减少了上下文切换的开销,但随着对应用系统性能核吞吐量要求的提高,出现了处理海量数据核请求的要求,这些都对高并发编程有着迫切的需求。
获取 CPU 的核数(虚拟内核)
System.out.println(Runtime.getRuntime().availableProcessors());
线程的状态
public enum State {
NEW,
RUNNABLE,
BLOCKED,
//等待
WAITING,
//超时等待
TIMED_WAITING,
TERMINATED;
}
① 来自不同的类
wait ->Object
sleep->Thread
企业中使用休眠的一般方式:
TimeUnit.DAYS.sleep(1);// 休眠一天
TimeUnit.SECONDS.sleep(1);// 休眠一秒
②关于锁的释放
wait 释放锁;
sleep 不释放锁;(抱着锁
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。