【问题标题】:How to store threads in arraylist如何在arraylist中存储线程
【发布时间】:2015-09-09 03:15:27
【问题描述】:

我有一个服务器和几个客户端。我为每个客户创建了一个线程。我想将每个客户端的线程或对象存储在数组列表中。并对其进行操作。

ArrayList<Client> clients;
Thread client = new Thread(new ClientThread(socket));

想要将每个客户端添加到客户端数组列表中。我已经创建了一个客户对象数组列表。

【问题讨论】:

  • ClientThreadClient 吗?
  • 客户端线程不是客户端。那是一个用于使用可运行的多线程的类。有 3 个类 Server Client 和 ClientThread
  • 那么Client 是什么?它从何而来?为什么要将其添加到ArrayList?它与您显示的线程有什么关系?你的问题有很多遗漏。
  • 我只是想在arraylist中添加线程
  • 想将每个客户端添加到客户端数组列表中是哪一个?

标签: java multithreading sockets arraylist


【解决方案1】:

假设您在某个实现 Runnable 的地方定义了 ClientThread,您可以这样做:

List<Thread> clients = new ArrayList<Thread>();
Thread client = new Thread(new ClientThread(socket));
client.start(); //assuming you want the thread to start
//running before you put into the arrayList
clients.add(client);

【讨论】:

  • 在添加时说不能从静态上下文中引用非静态变量客户端。 3号线
  • 线程客户端 = new Thread(new ClientThread(socket));客户端.start(); clients.add(client);
猜你喜欢
  • 2018-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
  • 2021-12-03
  • 2019-05-22
  • 2023-04-10
相关资源
最近更新 更多