目录
1进程与线程:
1.1进程:
一个操作系统中一个程序的执行周期
1.2线程:
一个进程同时执行多个任务。通常来讲,每个任务就可以成称为一个线程
1.3两者关系:
1.线程更加的“轻量级”,创造和撤销一个线程比启动撤销一个进程的开销小的多
一个进程中所有线程共享此进程的所有资源
2.没有进程就没有线程,进程一旦终止,线程也将不复存在
3.进程是操作系统资源调度的基本单位,进程可以共享资源
线程需要依靠进程提供的资源,无法独立申请操作系统资源,是os任务执行的基本单位。
高并发:
指的是同一时刻访问的线程量特别高
2多线程的实现:
2.1继承Thread类(单继承局限)
java.lang.Thread是线程操作的核心类.新建一个线程最简单的方法就是继承Thread类.而后覆写run()方法(相当于主线程的main()方法)
//无论使用哪种方式实现线程,线程的启动一定调用Thread类提供的start()方法
//start源码:
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 */
}
}
}
private native void start0();
由源码可知:
1线程的start()