简体   繁体   中英

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:

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() {
        //
    }

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM