定义

进程定义: 系统运行的基本单位,是程序一次执行的过程。进程之间基本是独立的。
线程定义:是比进程更小的运行单元,线程可以共享计算机的内存空间,线程之间存在互相影响。一个进程可以产生多个线程。

线程原理

  1. java当中产生线程代码,一般new Thread 然后调用threadstart方法,start 方法中其实最核心的是start0 方法,这个方法是个native 方法 也就是c的代码。在Thread 类的加载过程中 static 代码块中 会注册c的一些方法到jvm 中去,比如start0resume0interrupt0等。当调用start0 方法,先执行c代码,然后c代码 映射到jvmJVM_StartThread 方法 这个方法中创建了JavaThread 对象,这个对象会创建OSThread,然后这个对象才会真正使用pthread_create 去创建操作系统底层的线程。在JAVAThread c代码中又会回调到java代码的run方法
  1. int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
  2. void *(*start_routine) (void *), void *arg);
  1. private static native void registerNatives();
  2. static {
  3. registerNatives();
  4. }
  5. new Thread(new Runnable() {
  6. @Override
  7. public void run() {
  8. System.out.println("new thread");
  9. }
  10. }).start();
  11. public synchronized void start() {
  12. if (threadStatus != 0)
  13. throw new IllegalThreadStateException();
  14. group.add(this);
  15. boolean started = false;
  16. try {
  17. start0();
  18. started = true;
  19. } finally {
  20. try {
  21. if (!started) {
  22. group.threadStartFailed(this);
  23. }
  24. } catch (Throwable ignore) {
  25. /* do nothing. If start0 threw a Throwable then
  26. it will be passed up the call stack */
  27. }
  28. }
  29. }
  30. private native void start0();