定义
进程定义: 系统运行的基本单位,是程序一次执行的过程。进程之间基本是独立的。
线程定义:是比进程更小的运行单元,线程可以共享计算机的内存空间,线程之间存在互相影响。一个进程可以产生多个线程。
线程原理
java当中产生线程代码,一般new Thread 然后调用thread的start方法,start 方法中其实最核心的是start0 方法,这个方法是个native 方法 也就是c的代码。在Thread 类的加载过程中 static 代码块中 会注册c的一些方法到jvm 中去,比如start0,resume0,interrupt0等。当调用start0 方法,先执行c代码,然后c代码 映射到jvm的JVM_StartThread 方法 这个方法中创建了JavaThread 对象,这个对象会创建OSThread,然后这个对象才会真正使用pthread_create 去创建操作系统底层的线程。在JAVAThread 的c代码中又会回调到java代码的run方法
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
private static native void registerNatives();
static {
registerNatives();
}
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("new thread");
}
}).start();
public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
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();