简体   繁体   English

java:创建多个具有不同名称的线程(不使用for循环)

[英]java : Create multiple threads with different names (without using for loop)

I am working on a project where I have to create on or more new threads when a particular condition is satisfied. 我正在一个项目中,当满足特定条件时,我必须在一个或多个新线程上创建。 Basically I am stuck in creating new threads with different names every time as I am not aware how many threads would be generated in tun time. 基本上,每次我都停留在创建具有不同名称的新线程的过程中,因为我不知道在调整时间内会生成多少个线程。

Example : Thread t1= new thread(); 示例:线程t1 = new thread(); Thread t2= new thread(); 线程t2 = new thread(); and so on.. Here I am not aware of whether I would be requiring till t10 or t99. 依此类推。.在这里,我不知道我是否需要直到t10或t99。

I know you asked for no loop, but would this get what you need? 我知道您要求不循环,但这会满足您的需求吗?

int numberOfThreads = //whatever;
 ArrayList<Thread> threadList = new ArrayList<>();
 for(int i = 0; i<numberOfThreads; i++)
 {
    Thread t = new Thread();
    threadList.add(t);
}

You can call the threads by index instead of name, threadList.get(number); 您可以通过索引而不是名称threadList.get(number);来调用线程。

First things first: 第一件事:

There are no dynamical variables in java. Java中没有动态变量。 You've to declare them in the sourcecode. 您必须在源代码中声明它们。

To archieve your identifier problem you could use a HashMap : 要归档标识符问题,可以使用HashMap

Map<String, Thread> hm = new HashMap<String, Thread>();

And a method that adds threads to it: 还有一种向其添加线程的方法:

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.

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