JAVA 中的main方法是怎么执行的?

所有的java开发者兄弟,第一段代码都是 :

public static void main(String[] args) {
        System.out.println("hello word");
}
复制代码

但是,你有没有考虑过,为什么计算机可以执行这个方法,为什么这个方法的名字一定是 main,参数为什么是 String[] args ?

以下这段代码是 在linux内实现一个手动的线程

#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
 
void printids(const char *s)
{
    pid_t pid;
    pthread_t tid;
    pid = getpid();
    tid = pthread_self();
    printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int) pid,
            (unsigned int) tid, (unsigned int) tid);
}
 
void *thr_fn(void *arg)
{
    printids("new thread: ");
    return NULL;
}
 
int main(void)
{
    int err;
    pthread_t ntid;
    err = pthread_create(&ntid, NULL, thr_fn, NULL);
    if (err != 0)
        printf("can't create thread: %s\n", strerror(err));
    printids("main thread:");
    pthread_join(ntid,NULL);
    return EXIT_SUCCESS;
}
复制代码

其中,pthread_create,方法是在操作系统内创建一个线程,参数 1线程Id,参数三 thr_fn 就是 void *arg。

Java通过编译出一个可以由linux 线程调用main方法,然后通过JNI的反向调用,就可以执行了,
是不是很简单

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享