Java:从线程中一个接一个地调用方法

标签 java multithreading

我有 Server 类和 ClientThread 子类。 ClientThread 具有 receive() 和 Broadcast(String[] msg) 方法,用于从连接到服务器的客户端接收消息和向客户端发送消息。

方案:

public class Server extends Thread {
    private ArrayList<ClientThread> clientThreads;
    class ClientThread extends Thread {
        public void broadcast(String[] msg) {...}
        public void receive() {
            ...
            if (msg.equals("CHANGED")) {
                resumeOthers();
        }

        public void suspendOthers() {
            for (ClientThread c: clientThreads)
                 if (c!=this)
                     try {
                         c.wait();
                     } catch (InterruptedException e) {}
        }

        public void resumeOthers() {
            for (ClientThread c: clientThreads)
            if (c!=this)
                c.notify();
        }
    }

    public void run() {
        ...
        cmd = new String[1];
        cmd[0] = "PROMPTCHANGE";
        for (ClientThread currPlayer: clientThreads) {
            currPlayer.broadcast(cmd);
            currPlayer.suspendOthers();
        }
    }
}

现在,我想让这个 ClientThreads 依次工作,如下所示:

1. ClientThread number 1 is calling method broadcast.
Now any other ClientThread existing is freezed
(they are stored in ArrayList on Server)

2. Client (another class) replies with a message that is being caught by receive()
Now this thread is freezed, and the next one starts running

不幸的是,我的方法不起作用。 有人可以详细解释我如何实现这一目标吗?

最佳答案

通过调用 Object.wait(),您将挂起 CALLING 线程,而不是该对象所在的线程。

因此,实际上,您正在执行一个循环,该循环会阻塞调用线程 N 次,这绝对不是您想要的。

为了暂停线程,您需要让 IT 等待一个对象,或者让它阻止进入同步块(synchronized block)(或使用 Thread.sleep(),但通常这不是一个好的解决方案)。 换句话说,客户端线程需要调用 wait,而不是调用线程。

补充一点: 您似乎对 Java 线程和同步不熟悉,我强烈建议您在尝试此操作之前先阅读相关内容。

Google 搜索一些有关该主题的文档。 这里有一些可以帮助您开始的东西: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

关于Java:从线程中一个接一个地调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19481491/

相关文章:

java - 使用 System.currentTimeMillis() 测量时间差

java - 如何从数组创建多个 Java 对象实例?

java - 按顺序并发运行 Runnable

ios - swift ,dispatch_group_wait 不等待

java - JComboBox 事件 - Swing

java - 字符数组(Java)中空单元格的值是多少?

c - unix中的线程通信

Java新线程需要内存

java - 找不到类 com/google/common/util/concurrent/FutureFallback

c# - 如何等待任务执行结束来恢复程序的执行