进程和线程的区别:
进程的内存大小为:**堆内存+线程数量*栈内存,即线程数量 =( 最大地址空间[MaxProcessMemory] - JVM堆内存 - 系统保留内存[ReservedOsMemory] )/ ThreadStackSize(XSS),**从中可以看出,线程的数量随栈内存的增多而减少。
线程是程序执行的一个路径,每一个线程都有自己的局部变量表、程序计数器(指向正在执行的指令指针)以及各自的生命周期。当启动了一个Java虚拟机(JVM)时,从操作系统开始就会创建一个新的进程(JVM进程),JVM进程将会派生或者创建很多线程。
- 一个线程的创建肯定是由另一个线程完成的;
- 被创建线程的父线程是创建它的线程;
线程会带来额外的开销,如CPU调度时间、并发控制开销等;每个线程在自己的工作内存交互,加载和存储主内存控制不当会造成数据不一致。
一.线程创建方式:
构造Thread类:实现线程的执行单元run有两种方式,分别是下面
继承Thread,重写run方法:Thread实现了Runnable接口,使用start开启线程,start开启后线程会加入调度器,然后调用run方法,start会调用start0本地方法跟OS进行交互运行;下面是start源码解析
/**
-
Causes this thread to begin execution; the Java Virtual Machine
-
calls the
run
method of this thread. -
开启线程,JVM会调用run方法【start使用了模板方法】
-
-
It is never legal to start a thread more than once.
-
不能两次启动线程,否则报IllegalThreadStateException异常
-
In particular, a thread may not be restarted once it has completed
-
execution.
-
一个线程生命周期结束,也就是到了TERMINATED状态,再次调用start方法是不允许的,
-
也就是TERMINATED状态没法回到RUNNABLE/RUNNING状态。
* @exception IllegalThreadStateException if the thread was already
- started.
* @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”.
-
线程被构造后的new状态,threadStatus的属性值是0
*/
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 */
}
}
}
void add(Thread t) {
synchronized (this) {
if (destroyed) {//线程组状态校验
throw new IllegalThreadStateException();
}
if (threads == null) {