java线程对应操作系统线程初步探索

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调用线程初步探索。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值