7

I have got a main thread and within that thread I start a new thread. (the child thread). That child thread opens a server socket and starts listening for a connection. I want that thread to stop its execution and close whatever it has initialized (like the Socket) when the main thread gets a message from outside (from where it gets the the message is not the concern). How should I stop the thread and close all the connections is what I want.

Should I use a shared variable? so that when the main thread receives the message it should modify it and the child thread should continually check for the changes in that shared variable?

How should I implement it? Some useful links may help or a sample code ?

What I have tried is as follows: in the main thread I have 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 above code is not at all working. How should I do it?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
neerajDorle
  • 540
  • 7
  • 21

4 Answers4

6

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

childTread.interrupt();

and in the child thread, you do 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 isn't interruptible, so if you want to stop it from waiting, you will have to close it from outside, to force it to throw an IOException.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • How should I close it from outside? only my child thread has the knowledge of the Socket..... or should I declare it somewhere outside of the child thread? in the main thread? – neerajDorle May 06 '13 at 17:16
  • You could provide a `closeSocket` method in your child thread that closes the socket (and makes the `accept` throw an exception). You would need to call it from a different thread of course. – assylias May 06 '13 at 17:18
  • can you please go through this question and see if you can solve the problem ?? its on android -bluetooth http://stackoverflow.com/questions/16413498/blue-tooth-file-not-sent-error – neerajDorle May 07 '13 at 09:28
  • @user2354443 I have never used blutetooth connectivity so can't really help. – assylias May 07 '13 at 09:42
3

Child thread

You should make a new function here, f.e:

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

Parent Thread

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

 childThread.setFlag(1);

If you don't need the child Thread to be anonymous, create a ChildThread class:

 public ChildThread implements Runnable
{
    private int flag = 0;

    public ChildThread()
     {  }

    public void setFlag(int i)
      {
         flag = i;
      }
    public void run()
      { 
       //your code
      }
    ....
}
aran
  • 10,978
  • 5
  • 39
  • 69
  • I am not able to call childThread.setFlag(1) from the main thread..... It shows some error. – neerajDorle May 06 '13 at 12:00
  • change "childThread" for the name of your actual child thread ; ) – aran May 06 '13 at 12:00
  • t.setFlag(1), and in the thread i have public void setFlag(int i){ flag = i } – neerajDorle May 06 '13 at 12:04
  • isn't there any chat here? so that i can post the whole code to u – neerajDorle May 06 '13 at 12:05
  • do you have more classes defined with the same name? Rename your .java. Also, try to clean your project first. There seems to be an issue with the name of your classes.. – aran May 06 '13 at 12:12
  • no.my code for the thread is as follows: Thread t = new Thread(new Runnable(){ public void run(){ //initialize a server socket while(true){ if(read_flag==1){ break;} Sock1 = server_Sok.accept(); } } public int read_flag(){return flag;} public void setFlag(int i){falg=i} }); – neerajDorle May 06 '13 at 12:14
  • and from the main thread I am trying to call t.setFlag(1) when the particular message arrives – neerajDorle May 06 '13 at 12:18
  • Okay, so your are making new runnables INSIDE your parent one. Do you need this child threads to be anonymous, or you can create new ones? – aran May 06 '13 at 12:18
  • What I want to say is this: can you make, from your parent thread, this call? childThread t = new childThread(); --> this being another class, with its constructor. This class implements runnable as well, and has a run() method. Inside this class you put the setFlag function, and then, you can make the call from the parent this way: childThread t = new childThread(); t.start(); //this will make the thread enter the run() method; and, when you want: t.setFlag(i);... – aran May 06 '13 at 12:23
  • http://stackoverflow.com/questions/16413498/blue-tooth-file-not-sent-error can you please go through this question and see if you can solve the problem ?? its on android-bluetooth – neerajDorle May 07 '13 at 09:27
0

If you are using a flag to signal a thread to stop, make sure read/write access is synchronized. For example:


   public synchronized void cancel ()
   {
       stop = true;
   }

   protected synchronized boolean cancelRequested ()
   {
       return stop;
   }
Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
  • http://stackoverflow.com/questions/16413498/blue-tooth-file-not-sent-error can you please go through this question and see if you can solve the problem ?? its on android-bluetooth – neerajDorle May 07 '13 at 09:30
-1

Extend Runnable with your own implementation:

public class StoppableRunnable extends Runnable {

}

Code your class so that you can stop the execution of the Runnable, you will find a good example of how to do this here How to properly stop the Thread in Java?. Make sure you look at the first two answers.

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

Community
  • 1
  • 1
chopchop
  • 1,905
  • 2
  • 22
  • 37