![](/img/trans.png)
[英]java : Create multiple threads with different names (without using for loop)
[英]Java run multiple threads from for loop with different names
我試圖在for循環中啟動可變數量的線程,並想將線程命名為prime1,prime2,[...]。
PrimeFinderThread
類是從Thread擴展的。
[...]
for (int i = 0; i <= numberThreads; i++) {
PrimeFinderThread ("prime" + i) = new PrimeFinderThread (lowerBoundary, interval);
}
[...]
我收到錯誤消息:
作業的左側必須是變量。
來自("prime" + i)
用不同的名稱啟動X線程的可能解決方案是什么?
請嘗試以下操作:
Thread[] threads = new PrimeFinderThread[numberThreads];
for (int i = 0; i < numberThreads; i++) {
threads[i] = new PrimeFinderThread (lowerBoundary, interval);
threads[i].setName("prime" + i);
threads[i].start();
}
它通過setName
-method設置名稱,然后通過調用start
來start
每個線程。
但是,使PrimeFinderThread
的構造PrimeFinderThread
接受一個額外的參數(即name
並調用超類構造函數可能更容易。
public PrimeFinderThread (String name, int lowerBoundary, int interval) {
super(name); // instead of setName
// Do the other stuff
}
IMO,一種更好的方法是不擴展Thread
類,而是提供Runnable
,最好提供某種ExecutorService
檢查例如Executors JavaDoc或Oracle網站上的並發跟蹤 。
對於Java中的賦值,您不能在=
運算符的左側指定其他參數。 因此PrimeFinderThread ("prime" + i)
是並且將保持無效。
相反,您應該簡單地為構造函數定義一個附加參數,然后使用super
關鍵字結構將其傳遞給父類構造函數。
您應該將創建的線程分配給某個變量
PrimeFinderThread[] threads = new PrimeFinderThread[numberThreads];
for (int i = 0; i < numberThreads; i++) {
threads[i] = new PrimeFinderThread ("prime" + (i+1), lowerBoundary, interval);
threads[i].start();
}
至於設置每個線程的名稱,這取決於PrimeFinderThread類具有哪些構造函數。 您可以將線程名稱傳遞給PrimeFinderThread
的構造PrimeFinderThread
,然后從那里將其傳遞給Thread
的構造函數。
例如:
public PrimeFinderThread (String name, int lowerBoundary, int interval)
{
super (name);
...
}
在Java的左側分配中,不能使用X指定其他參數。 要給線程命名,您可以從線程的子類或線程中調用super(threadName)。可以使用setName(“ threadName”)。
public class ThreadSubClass extends Thread{
public ThreadSubClass(String threadName){
super(threadName);
}
@Override
public void run(){
System.out.println("Entering : " + getName());
//do Something
}
public static void main(String [] args){
for(int i=0;i<5;i++){
ThreadSubClass t = new ThreadSubClass("Prime"+i);
t.start();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.