简体   繁体   English

线程在继续之前等待服务器/客户端

[英]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:我的 output 看起来像这样: Please enter number: Please enter number:

But it should look like this:但它应该看起来像这样:

Please enter number: User enters number Please enter number:用户输入号码

Please enter number: User enters number Please enter 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()我想你正在寻找这个Thread.join()

How to use it?如何使用它?

If you have one client, say Client client1 = new Client();如果您有一个客户,请说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.在线程上执行join()会使启动这个新线程到 go 的线程变成等待的 state。 It remains in waiting state until the thread that join() was performed upon terminates or is interrupted.它一直在等待 state 直到执行join()的线程终止或中断。 Any code after join() is not executed until the thread on which this method was called, terminates.在调用此方法的线程终止之前,不会执行join()之后的任何代码。

In your case, the main thread goes into waiting state.在您的情况下,主线程进入等待 state。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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