开发者

Can you assign unique thread ids and access thread from external program?

I am currently implementing a program that requires me to handle threads and process.

IDEA:

  1. There are multiple java processes running and each process may have multiple threads. Current java implementation is such that 开发者_Python百科thread ids in java is unique for a particular process but not within the processes. So is there a way I could implement a unique thread ids among multiple processes?

  2. Also, I need to implement an external java program that monitors these threads. By monitoring I mean, depending upon some logic I need to notify a particular thread(using unique thread id) regarding an event. Is there a way that I can access thread from external program. If yes how?

  3. Are there any other solutions to implement the similar idea?

Thank you in advance.


You could use a concatenation of the process id and the thread id to uniquely identify a thread - for instance, thread 23 in process 7038 could be identified as 7038:23. This has the advantage that given a thread identifier, you can tell which process the thread belongs to.

I doubt that it is possible for one process to control the threads of another. You probably need to use some form of inter-process communication, such as RMI, named pipes, or TCP. Each process should probably have one thread that waits for an incoming message, parses it, and notifies the appropriate thread based on the contents of the message.

A very simple example of what a TCP-based solution might look like: Every worker process has a thread that listens for TCP connections from the monitoring process; it is expected that when the monitoring process connects, it will write one line containing the id of a thread in this worker process. The worker process must keep e.g. a HashMap that maps thread ids to Thread objects.

ServerSocket socket = new ServerSocket(6789);
while (true) {
    Socket connectionSocket = welcomeSocket.accept();
    BufferedReader socketReader = new BufferedReader(new InputStreamReader(
                                      connectionSocket.getInputStream()));
    String line = socketReader.readLine();
    int threadId = Integer.parseInt(line);
    // Now, use threadId to locate the appropriate thread 
    // and send a notification to it.
}

There should probably also be a way for the monitoring process to ask a worker process for all its thread ids. The worker process can simply maintain a list of process ids (and which port each process listens to) and, for each process id, a list of the thread ids inside that process.

By the way, as @parsifal said, it would be interesting to know what you are actually trying to achieve.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜