[英]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.