简体   繁体   English

在这种情况下如何使用Thread.join()?

[英]How do I use Thread.join() in this situation?

I'm writing a simple roulette game that can take multiple players at a time. 我正在编写一个简单的轮盘游戏,一次可以容纳多个玩家。 I'm trying to deserialize a .dat file players.dat , however I'm getting a FileNotFoundException that I suspect is due to my main thread running concurrently to another thread. 我正在尝试反序列化.dat文件players.dat ,但是我收到一个FileNotFoundException ,我怀疑这是由于我的主线程同时运行到另一个线程。

My main file (note that readObj is simply a convenience method that uses ObjectInputStream to read the object back): 我的主文件(请注意, readObj只是使用ObjectInputStream读回对象的便捷方法):

    Collection<Player> mPlayerList = null;

    try {
        connectToServer();
    } catch (IOException e) {
        System.err.println("IO exception when trying to write/connect to server");
        e.printStackTrace();
    }

    // read input stream and attempt to deserialize
            // stack trace points to the error being from here
    try {
        mPlayerList = (Collection<Player>) readObj("players.dat");
    } catch (IOException e) {
        System.err.println("IO exception when trying to read master player list");
        e.printStackTrace();    
        System.exit(1);     
    } catch (ClassNotFoundException e) {
        System.err.println("Class not found exception when trying to read master player list");
        e.printStackTrace();    
        System.exit(1);                 
    }

In my first try statement, I attempt to connect to a server running off of my computer: 在我的第一个try语句中,我尝试连接到在我的计算机上运行的服务器:

public class GameEngineServerStub {

public static void main(String[] args) throws IOException {

    GameEngineImpl myEngine = new GameEngineImpl();

    int portNumber = 4444;
    boolean listening = true;

    // While statement loops forever, waiting for a client to connect.
    // Once client connects, accept, create a new Thread, pass the socket to it, and requests it to start
    try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
        while (listening) { 
            new GameEngineServerStubThread(serverSocket.accept(), myEngine).start();
        }
    } catch (IOException e) {
        System.err.println("Could not listen on port 4444");
        System.exit(-1);
    }

}

 }

The server launches this thread, which is responsible for requesting a Collection<Player> object from another file, and attempting to serialize it. 服务器启动此线程,该线程负责从另一个文件请求Collection<Player>对象,并尝试对其进行序列化。

public void run() {

    try (
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    ) {

        Collection<Player> currentPlayers = engine.getAllPlayers();

        try {
            ObjectOutputStream objOut = new ObjectOutputStream(new FileOutputStream("players.dat"));
            objOut.writeObject(currentPlayers);
        } catch (IOException e) {
            System.err.println("IO Exception when trying to get master player list!");
            e.printStackTrace();
            System.exit(1);                     
        }

    } catch(IOException e) {
        e.printStackTrace();
    }

}
}

I assume that I will need to pause my main thread, to wait for my serialization thread to finish, but I'm unsure of how to do so. 我假设我需要暂停main线程,以等待序列化线程完成,但是我不确定该怎么做。

I'm unsure of some aspect of your question, but there are a series of things you could do depending on your situation 我不确定您的问题的某些方面,但是您可以根据自己的情况采取一系列措施

Your server and client are running on different JVMs 您的服务器和客户端在不同的JVM上运行

This case you need an inter process locks which is hard to do, you could try JCIP maybe you could look at here to get some ideas 这种情况下,您需要一个很难做到的进程间锁,您可以尝试JCIP,也许您可以看这里以获取一些想法

Your server and client are running on the same JVM but in different threads 您的服务器和客户端在同一JVM上运行,但线程不同

This case it's much easier, you can use the number of java's locks to achieve this, for example the easiest would be to create a ReentrantReadWriteLock and pass it to both threads and make the server hold the write lock until the serialization is done, and make the client block on the read lock. 这种情况要容易得多,您可以使用Java锁的数量来实现这一点,例如,最简单的方法是创建一个ReentrantReadWriteLock并将其传递给两个线程,并使服务器持有写锁,直到完成序列化为止,然后客户端块上的读取锁。 You could read more about locks and locking in java here and here 您可以在此处此处阅读有关锁和锁的更多信息。

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

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