Java JUC并发之初识JUC与多线程回顾
一、什么是JUC?
学习方法: 源码 + 官方文档
面试高频问!!
JUC: java.util.concurrent 并发包 包含三个子包
java.util 工具包 屏蔽同名
业务 : 普通的线程代码 Thread
Runnable 没有返回值、效率相比 Callable 较低!
Callable接口文档:
Lock 文档:
二、 线程 和 进程
进程: 一个正在执行的程序称为进程 一个进程往往可以包含多个线程(至少一个)系统资源分配的单位
线程:CPU执行和调度的单位 JAVA默认有几个线程? 2个 main、GC
Thread 、Runnable、Callable
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();
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(); // 调用本地方法,Java无法直接操作硬件
/**
* If this thread was constructed using a separate
* {@code Runnable} run object, then that
* {@code Runnable} object's {@code run} method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of {@code Thread} should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
if (target != null) {
target.run();
}
}
并发、并行
并发编程 : 并发 并行
并发: 多线程操作同一个资源 交替进行
- CPU 单核 模拟(假象) 多条线程 快速交替
并行:多个人一起行走 同时进行
- CPU 多核,多个线程可以同时执行 线程池
package com.liu.demo01;
public class Test01 extends Thread{
public static void main(String[] args) {
// new Thread().start();
// 获取CPU的核数
// CPU密集型、IO密集型
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
并发编程的本质: 充分利用CPU的资源
线程有几个状态 5大状态(6个)
State :
- new // 新生
- runnable 运行
- blocked 阻塞
- waiting 等待,一直等待
- Timed_waiting 超时等待
- terminated 终止
wait() 与 sleep() 的区别
-
来自不同的类
wait() => Object
sleep() => Thread
-
关于锁的释放
wait会释放锁
sleep抱着锁睡觉 => 不会释放锁
-
使用的范围是不同的
wait 必须在同步代码块 / 同步方法中使用
sleep 可以在任何地方使用
-
是否需要捕获异常
wait 不需要捕获异常
sleep 必须捕获异常
本文来自博客园,作者:{夕立君},转载请注明原文链接:https://www.cnblogs.com/xili-sanriyue/p/15016126.html