线程
线程在Java中的实现主要是通过实现操作系统中的方法,也就是说Java中要起一个线程,必须通过JVM调用底层native方法才能实现开启线程。也就是说Java线程只是系统的一个封装实现,所以想了解Java的线程,就必须理解操作系统层面的实现。
Linux的线程实现方式
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
上面的代码是Linux新建一个线程的方法,也是JVM新建线程的方法,当我们启动一个线程的时候,源码中会调用一个start0()方法。start0()是JVM的一个navtive方法。
public class testnew {
public class testnew {
public static void main(String[] args) {
Thread thread = new Thread(){
@Override
public void run() {
System.out.println("i am new Thread! from java ");
}
};
thread.start();
}
}
}
而start0() 方法就是就是调用了Linux的pthread_create方法,这个方法第一个参数是pthread_t *thread ,代表是线程地址,被创建的线程id。const pthread_attr_t *attr 线程属性,默认null;void(start_routine)(void *) 线程的主体函数,需要定义一个函数,然后传进函数名即可。void *arg 主体函数的参数。
//头文件
#include <pthread.h>
#include <stdio.h>
//定义一个变量,接受创建线程后的线程id
pthread_t pid;
//定义线程的主体函数
void* thread_entity(void* arg) {
printf("i am new Thread! from c");
}
//main方法,程序入口,main和java的main一样会产生一个进程,继而产生一个main线程
int main() {
//调用操作系统的函数创建线程,注意四个参数
pthread_create(&pid,NULL,thread_entity,NULL);
//usleep是睡眠的意思,那么这里的睡眠是让谁睡眠呢?
//为什么需要睡眠?如果不睡眠会出现什么情况
usleep(100);
printf("main\n");
return 0;
}
实现JVM虚拟机上的线程功能
假如我们想在JVM中实现相关的线程功能,需要下面的调用方法。Java类使用JNI调用C文件中的方法,其中该方法中有pthread_create()方法,该方法调用了操作系统的新建线程方法,从而达到直接新建线程的方法调用,而不是new Thread。过程概况如下:Java通过JNI调用C中的方法,然后再调用操作系统中的线程。