The relationship between parent and child threads in Java

I have a main thread, and inside this thread I start a new thread. (child thread). This child stream opens the server socket and starts listening on the connection. I want this thread to stop executing and close everything that it initialized (for example, Socket) when the main thread receives the message from the outside (where it receives the message from is not a problem). How should I stop the thread and close all the connections that I want.

Should I use a shared variable? so when the main thread receives the message, it must change it, and the child thread must constantly check for changes in this shared variable?

How do I implement it? Some useful links might help or sample code?

What I tried looks like this: in the main thread, I declared a variable

flag=0; 

when the main thread receives the message, it sets

 flag = 1 ; 

and the thread listens for the change as follows:

  void ()run{ while(true){ if(flag==1){ break; } sock1 = Ssocket.accept(); } 

But the code above does not work at all. How can I do it?

+7
source share
4 answers

The proper way to interrupt a thread is to interrupt. In your main thread, when you want to stop the child thread, you call:

 childTread.interrupt(); 

and in the child thread you are doing something like:

 public void run() { try { while (!Thread.currentThread.isInterrupted) { sock1 = Ssocket.accept(); //rest of the code here } } catch (InterruptedException e) { Thread.currentThread.interrupt(); //good practice } //cleanup code here: close sockets etc. } 

Note that Ssocket.accept not interrupted, so if you want to stop it from waiting, you will have to close it from the outside to make it throw an IOException .

+6
source

Child thread

Here you have to make a new function, fe:

 public void setFlag(int i) { flag = i; } 

Parent Thread

Whenever you want to kill / stop listening / ... in a child thread, make a call:

  childThread.setFlag(1); 

If you do not need a child thread for anonymity, create the ChildThread class:

  public ChildThread implements Runnable { private int flag = 0; public ChildThread() { } public void setFlag(int i) { flag = i; } public void run() { //your code } .... } 
+3
source

If you use a flag to signal that the stream has stopped, make sure that read / write access is synchronized. For example:

 public synchronized void cancel () { stop = true; } protected synchronized boolean cancelRequested () { return stop; } 
0
source

Extend Runnable your own implementation:

 public class StoppableRunnable extends Runnable { } 

Build your class to stop Runnable , you will find a good example of how to do it here. How to stop Thread in Java correctly? . Make sure you look at the first two answers .

In your equivalent of terminate() function do all the cleanup

-one
source

All Articles