[英]java : Create multiple threads with different names (without using for loop)
我正在一个项目中,当满足特定条件时,我必须在一个或多个新线程上创建。 基本上,每次我都停留在创建具有不同名称的新线程的过程中,因为我不知道在调整时间内会生成多少个线程。
示例:线程t1 = new thread(); 线程t2 = new thread(); 依此类推。.在这里,我不知道我是否需要直到t10或t99。
我知道您要求不循环,但这会满足您的需求吗?
int numberOfThreads = //whatever;
ArrayList<Thread> threadList = new ArrayList<>();
for(int i = 0; i<numberOfThreads; i++)
{
Thread t = new Thread();
threadList.add(t);
}
您可以通过索引而不是名称threadList.get(number);来调用线程。
第一件事:
Java中没有动态变量。 您必须在源代码中声明它们。
要归档标识符问题,可以使用HashMap
:
Map<String, Thread> hm = new HashMap<String, Thread>();
还有一种向其添加线程的方法:
public void addThreadToMap(Thread t) {
hm.put("t" + hm.size().toString(), t); //This will add the thread with the key [t0 .... tn]
}
您可以只创建一个ArrayList并每次添加一个新的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.