【问题标题】:How to create threads in a loop, in an anonymous class referring to the loop variable?如何在引用循环变量的匿名类中创建循环中的线程?
【发布时间】:2015-03-26 20:20:29
【问题描述】:

我正在做一个并发服务器程序并且我正在测试它。 在 JUnit 测试中,我输入以下内容:

[...]

Client[] clients = new Client[30];
for ( int i = 0; i<30 ; i++){
    clients[i] = new Client("localhost", SERVPORT);
}

for ( Integer i = 0; i<30 ; i++){
    new Thread(){
        public void run(){
            clients[i].send(i.toString()); <--
        }
    }.start();
}
[...]

问题是 Java 无法编译,因为我无法在以不同方法定义的内部类中引用非最终变量 i,因此我必须修改 i 并将其写为 final(但我不应该这样做) .我明白,但是...如何同时从所有客户端发送消息?

附加信息: 在send(String)方法中,我向服务器发送消息,等待服务器响应。

【问题讨论】:

  • 为什么i是Integer而不是int有什么原因吗?
  • 因为我想发送到服务器 i.toString() 并且对于该方法,我需要一个整数而不是整数的对象
  • 你知道你可以使用Integer.toString(n)这个静态方法,其中nint,而不需要实际创建一个Integer对象?
  • 非常感谢,我不记得了!

标签: java multithreading loops server


【解决方案1】:

您可以在原始for 循环中运行线程,通过引用局部变量来跳过索引变量i 的使用:

final Client[] clients = new Client[30];
for (int i = 0; i < 30; i++) {
    final Integer integer = new Integer(i);
    final Client client = new Client("localhost", SERVPORT);
    clients[i] = client;
    new Thread(){
        public void run(){
            client.send(integer.toString());
        }
    }.start();
}

注意为每个循环创建的 final 整数。

【讨论】:

    【解决方案2】:

    你可以这样做:

    for(int i = 0; i < clients.length; i++){
      new Thread(()->{
         clients[i].send(i+"");
      }).start();
    }
    

    【讨论】:

    • 这个答案出现在低质量审查队列中,大概是因为您没有解释代码。如果你确实解释了(在你的回答中),你更有可能获得更多的支持——提问者更有可能学到一些东西!
    【解决方案3】:

    您可以在构造函数中定义自己的接受客户端参数的线程类。

    class MyThread extends Thread
    {
        private Client client;
        private String message;
        MyThread(Client client, String message)
        {
            this->client = client;
            this->message = message;
        }
        public void run()
        {
            client.send(message);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 2023-02-01
      • 2021-05-01
      • 2019-10-04
      • 2016-05-26
      相关资源
      最近更新 更多