简体   繁体   English

Java线程和OS线程之间的通信

[英]Communication between Java thread and OS threads

As for as I know, Java threads can communicate using some thread APIs. 据我所知,Java线程可以使用一些线程API进行通信。 But I want to know how the Java threads and the OS threads are communicting with each other. 但我想知道Java线程和OS线程是如何相互通信的。 For example a Java thread needs to wait for some OS thread finishes its execution and returns some results to this Java thread and it process the same. 例如,Java线程需要等待某个OS线程完成其执行并将一些结果返回给此Java线程并且它处理相同的内容。

Many mix up threads and processes here, the jvm is a process which may spawn more threads. 很多人在这里混淆线程和进程,jvm是一个可能产生更多线程的进程。 Threads are lighter processes which share memory within their process. 线程是较轻的进程,在其进程中共享内存。 A process on the other hand lives in his own address space, which makes the context switch more expensive. 另一方面,进程存在于他自己的地址空间中,这使得上下文切换更加昂贵。 You can communicate between different processes via the IPC mechanisms provided by your OS and you can communicate between different threads within the same process due to shared memory and other techniques. 您可以通过操作系统提供的IPC机制在不同进程之间进行通信,并且由于共享内存和其他技术,您可以在同一进程中的不同线程之间进行通信。 What you can't is communicate from ThreadA(ProcessA) to ThreadA(ProcessB) without going through plain old IPC: ThreadA(ProcessA) -> ProcessA -> IPC(OS) -> ProcessB -> ThreadA(ProcessB)). 你不能通过普通的旧IPC从ThreadA(ProcessA)到ThreadA(ProcessB)进行通信: ThreadA(ProcessA) -> ProcessA -> IPC(OS) -> ProcessB -> ThreadA(ProcessB)).

You can use RMI to communicate between two java processes, if you want to "talk" to native OS processes, you have to go JNI to call the IPC mechanisms your OS of choice provides imo. 您可以使用RMI在两个java进程之间进行通信,如果要与本机OS进程“对话”,则必须使用JNI来调用您选择的操作系统提供的IPC机制。

Feel free to correct me here :) 随意在这里纠正我:)

Sidenote: You cant see the threads of your JVM with a process manager (as long as your JVM does not map threads to native processes, which would be stupid but possible), you need to use jps and jstack to do that. 旁注:您无法使用流程管理器查看JVM的线程(只要您的JVM不将线程映射到本机进程,这可能是愚蠢但可能),您需要使用jps和jstack来执行此操作。

每个JVM实例本质上都是一个操作系统进程。

Java threads usually but don't necessarily run on native threads and Java concurrency classes could but don't necessarily map onto native equivalents. Java线程通常但不一定在本机线程上运行,Java并发类可以但不一定映射到本机等效项。

If you had to sync between a native thread and a Java thread, you will most likely have to consider writing a JNI method that your Java thread calls. 如果必须在本机线程和Java线程之间进行同步,则很可能必须考虑编写Java线程调用的JNI方法。 This JNI method would do whatever native synchronization operation it needs to do and then return. 此JNI方法将执行它需要执行的任何本机同步操作,然后返回。 Every platform is going to do this differently but I assume this wouldn't be too much of an issue if you need to inspect native threads in the first place. 每个平台都会以不同的方式执行此操作,但我认为如果您需要首先检查本机线程,这不会是一个太大的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM