线程和进程
进程:一个程序,例如QQ.exe Music.exe 程序集合
一个进程往往可以包含多个线程,至少包含一个
java默认有几个线程?2个 main、GC
线程:开了一个进程Typora,写字,自动保存(线程负责的)
对于java而言:Tread、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();
2.1、并发与并行
并发编程:并发、并行
并发(多个线程操作同一个资源)
- CPU一核,模拟出来多条线程,用的是快速交替
并行(多人一起行走)
- CPU多核,多个线程可以同时执行:线程池
package com.zkw.JUC并发编程;
public class Test01 {
public static void main(String[] args) {
//获取CPU的核数
//CPU 密集型,IO密集型
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
并发编程的本质:充分利用CPU资源
2.2线程有几个状态
// 新生
NEW,
//运行
RUNNABLE,
// 阻塞
BLOCKED,
// 等待,没有时间限制
WAITING,
// 超时等待,有时间限制,只要时间限制到就不在等待
TIMED_WAITING,
// 终止
TERMINATED;
2.3、wait/sleep区别
2.3.1、来自不同的类
wait=>Object
扫描二维码关注公众号,回复:
13198441 查看本文章
sleep=>Thread
2.3.2、关于锁的释放
wait会释放,sleep不会释放
2.3.3、使用的范围是不同的
wait必须在同步代码块中
sleep可以在任何地方使用