线程与进程
进程只是用来把资源集中到一起(进程只是一个资源单位,或者说资源集合),而线程 才是 CPU 上的执行单位。每个进程默认有一个控制线程(主线程),在一个进程当中存在多个控制线程,多个线程共享进程的地址空间,一个线程 不能单独执行,必须依存于进程。一个线程可以创建与销毁另一个线程(子线程)。同一个进程的多个线程可以并发执行。
并发与并行
无论是并行还是并发,在用户看来都是'同时'运行的,不管是进程还是线程,都只是一 个任务而已,真是干活的是 cpu,cpu 来做这些任务,而一个 cpu 同一时刻只能执行一个 任务。
并行(串行)
是伪并行,即看起来是同时运行。单个 cpu+多道技术就可以实现并发。
并发
同时运行,只有具备多个 cpu 才能实现并行 单核下,可以利用多道技术,多个核,每个核也都可以利用多道技术(多道技术是针对 单核而言的) 有四个核,六个任务,这样同一时间有四个任务被执行,假设分别被分配给了 cpu1, cpu2,cpu3,cpu4,可能任务 1 遇到 I/O 就被迫中断执行,此时任务 5 就拿到 cpu1 的。
时间片去执行,这就是单核下的多道技术,而一旦任务 1 的 I/O 结束了,操作系统会重新 调用它(进程的调度、分配给哪个 cpu 运行,由操作系统说了算),可能被分配给四个 cpu 中的任意一个去执行。
总结
并发:系统具有处理多个任务的能力
并行:系统具有同时处理多个任务的能力
注意:并发可以说是并行的一个子集,但不能说并行是并发
线程的生命周期
start()源码
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* 此线程开始执行时,jvm调用这个线程的run方法
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* 多次调用线程的start()启动一个线程时非法的
* In particular, a thread may not be restarted once it has completed
* execution.
* 特别的是,线程在执行完成之后不能再次调用
*
* @exception IllegalThreadStateException if the thread was already
* started.
* 已经启动的线程再次 start 会抛出线程非法状态异常
* @see #run()
* @see #stop()
*/
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) //判断线程状态是否为0 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(); //调用native方法执行run方法
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(); // native 方法,C++ 程序执行