Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Thread wait for Server/Client before proceeding

How do I synchronize threads while using one server and multiple clients?

public static void main(String[] args) {
        
    // Creates and starts instance of the "Server" class
    Server s = new Server();
    s.start();
    
    // Creates and starts 2 instances of the "Client" class
    for(int i=0; i<2; i++) {
        Client c = new Client();
        c.start();
    }
        
}

My output looks like this: Please enter number: Please enter number:

But it should look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please enter number: User enters number

Please enter number: User enters number

Both client and server classes are looking familiar like this:

public class Client extends Thread {

    public void run() {
        //
    }

}

>Solution :

I suppose you are looking for this Thread.join()

How to use it?

If you have one client, say
Client client1 = new Client();

And you want that another client should run after this client has finished its task, then you create a new client like this.

client1.start();
client1.join();
Client client2 = new Client();
client2.start();

You can use it in loop like this:

for(int i=0; i<2; i++) {
    Client client = new Client();
    client.start();
    client.join();
}

How does it work?

Performing join() on a thread makes the thread that started this new thread to go into a waiting state. It remains in waiting state until the thread that join() was performed upon terminates or is interrupted.
Any code after join() is not executed until the thread on which this method was called, terminates.

In your case, the main thread goes into waiting state.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading