持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第8天
多线程进阶-JUC
1.什么是JUC
java.utils工具包,包,类
业务:普通的线程代码 Thread
Runnable 没有返回值 , 效率相比Callable相对低下
2.线程和进程
线程,进程,如果不能用一句话说出来,基础不扎实
进程:一个程序,QQ.exe Music.exe 程序的集合;
一个进程往往可以包括多个进程 ,至少包含一个;
线程: 开了一个进程Typora,写字,自动保存(线程负责的)
java默认包含几个进程?
答:2个 main,GC
对java而言的话: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 */
}
}
}
//本地方法,底层c++ , java无法直接操作硬件
private native void start0();
并发,并行
并发编程:并发,并行
并发(多线程操作同一个资源)
- CPU 一核,模拟出来多个线程,天下武功,唯快不破,快速交替。
并行 (多个人一起行走)
- CPU多核,多个线程可以同时执行;线程池
public class Test1 {
public static void main(String[] args) {
//获取CPU核数
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
并发编程的本质:充分利用CPU的资源
所有的公司都很看重!
线程有几个状态
- new ------ 新生
- RUNNABLE ------ 运行
- BLOCKED ------ 阻塞
- WAITING ------ 等待(死死的)
- TIME_WAITING ------ 超时等待
- TEMINATED ------ 终止
wait/sleep 区别
1.来自不同的类
wait ==> Object
sleep ==> Thread
2.关于锁的释放
wait会释放锁
sleep睡觉了,拖着睡觉了,不会释放
3.使用的范围是不同的
wait:必须在同步代码快中使用
sleep:可以在任意的地方睡
4.是否需要捕获异常
wait: 不需要捕获异常
sleep: 必须捕获异常
总结
了解到之前学的多线程的锁和synchronize是个java的皮毛而已,现在开始更深入一点学习。