Johan
Johan

Reputation: 495

Interrupting threads in java

I've studied Java for almost 8 months now and I'm a little confused abouth interrupting threads.

I have a JavaFX multiThreaded application which displays all the clients connected (ip and port etc.) in a tableview.

When the program starts, I enter port number and press start button, which starts the server class.

I have a serverclass which implements Runnable, and when a client connects, I create an object of client class which extends Thread. Both the server and client class has in its run method:

public void run(){
    while (!Thread.currentThread().isInterrupted()){

the server creates a client like this:

new Thread(new Client(socket)).start();

And what I wonder is if I create a stop button, which invokes a method in the server class that interrupts the server thread, will the client threads automatically be interrupted too?

What I actually want is to be able to change the port without restarting the program. And of course I don't want threads to keep running in the background if I change to another port.

What options do I have in this case? If you miss any information, just leave a comment and I will fix it right away.

Upvotes: 1

Views: 84

Answers (1)

jado
jado

Reputation: 954

Since the Server and Client are on different Threads, if you interrupt the Server Thread, it will not interrupt the Client Thread. Threads started in other Threads are independent of their parent, so if the parent Thread stops, the child Thread can keep running.

Thread t = new Thread(new Runnable(){

    new Thread(new Runnable(){
        for(int i = 0; i < 1000; i++) System.out.println(i);
    }).start;

}).start();

t.interrupt();

The child Thread should keep running the program, as it is in a different Thread than the parent. The main job of the parent Thread is to start the child Thread, and if it dies, the child keeps on living.

Upvotes: 2

Related Questions