linux操作系统的线程控制:
yum -y install man-pages
man pthread_create
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
pthread_t *thread
|
传出参数,调用之后会传出被创建线程的id
|
定义 pthread_t pid取地址 &pid
|
const pthread_attr_t *attr
|
线程属性
|
传NULL,保持默认属性
|
void *(*start_routine) (void *)
| 线程执行的主体函数 |
你定义一个函数,然后传对应函数名
|
void *arg
|
主体函数的参数
|
如果没有可以传NULL
|
编写一个java类:
public class DouFuThread {
//装载库,保证JVM在启动的时候就会装载
static {
System.loadLibrary("DouFuThreadNative");
}
public static void main(String[] args) {
DouFuThread douFuThread = new DouFuThread();
douFuThread.start0();
}
public void run(){
System.out.println("i am new Thead");
}
private native void start0();
}
上传到linux服务器:
javac DouFuThread.java 编译class文件
javah DouFuThread 编译对应的.h文件
DouFuThread .h文件:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class DouFuThread */
#ifndef _Included_DouFuThread
#define _Included_DouFuThread
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: DouFuThread
* Method: start0
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_DouFuThread_start0
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
编写c程序,自定义runThread.c文件
#include <pthread.h>
#include <stdio.h>
#include "DouFuThread.h"
pthread_t pid;
void* thread_entity(void* arg) {
}
JNIEXPORT void JNICALL Java_DouFuThread_start0(JNIEnv *env, jobject c1) {
jclass cls;
jobject obj;
jmethodID cid;
jmethodID rid;
jint ret = 0;
// Class
cls = (*env)->FindClass(env,"DouFuThread");
if(cls == NULL) {
printf("FindClass error!\n");
return;
}
// method
cid = (*env)->GetMethodID(env,cls,"<init>","()V");
if(cid == NULL) {
printf("query constructor error!\n");
return;
}
// class.newInstance
obj = (*env)->NewObject(env,cls,cid);
if(obj == NULL) {
printf("NewObject error!\n");
return;
}
//method
rid = (*env)->GetMethodID(env,cls,"run","()V");
//method.invoke
ret = (*env)->CallIntMethod(env,obj,rid,NULL);
printf("finish call method!\n");
}
int main(){
return 0;
}
gcc -fPIC -I /usr/local/software/jdk1.8.0_251/include -I /usr/local/software/jdk1.8.0_251/include/linux -shared -o libDouFuThread.so runThread.c -pthread 将runThread.c编译成一个动态链接库DouFuThreadNative.os
export
LD_LIBRARY_PATH
=
$
LD_LIBRARY_PATH
:{
libLubanThreadNative
.
so
} 暴露链接库地址
java调用线程初步探索。