JUC概述
JUC概述
-
java.util.concurrent 简称juc
-
线程和进程
-
进程:一个程序
在操作系统中运行的程序就是进程,比如你的QQ,微信,游戏,ide等等…
一个进程可以包含多个线程,至少包含一个
Java默认有几个线程?
2个, main线程,GC线程(垃圾回收)
-
线程:
一个进程可以有多个线程,比如视频中同时听到声音,看到图像,看弹幕等等…
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 static void main(String[] args) { //获取cpu的核数 //cpu 密集型、io 密集型 System.out.println(Runtime.getRuntime().availableProcessors()); }并发编程的本质:充分利用CPU的资源
-
线程有几个状态
public enum State { // 新生 NEW, //运行 RUNNABLE, //阻塞 BLOCKED, //等待,往死里等 WAITING, // 超时等待 TIMED_WAITING, // 终止 TERMINATED; } -
wait/sleep的区别
| wait | sleep | |
|---|---|---|
| 来自不同的类 | Object | Thread |
| 关于锁的释放 | 会释放锁 | 不会释放,抱着锁睡觉 |
| 使用范围的不同 | 必须在同步代码块中 | 在任何地方都可以使用 |
| 是否需要捕获异常 | 不需要捕获异常 | 必须要捕获异常 |

浙公网安备 33010602011771号