[英]Storing multiple Threads in Java
假設我有一個實現Runnable
接口的類,我將在主程序中創建給定類的5個實例。 我想將它們存儲在數組或集合中。 由於該類實現了Runnable
,因此我的理解是,我可以存儲它的唯一方法是在線程容器中,例如Thread[]
。 但是,如果我這樣做,我不能使用重寫toString()
方法的類,或任何其他自定義方法/字段。
public class LittleClass implements Runnable{
public void run(){
}
}
public static void main(String[] args){
Thread[] smallClasses = new Thread[5];
// initialize and so...
smallClasses[i].customField//not accessible
System.out.println(smallClasses[i])//gives Thread[Thread-X,X,]
}
您應該考慮使用ExecutorService
。 然后,您保留一系列工作類,並將它們提交給要運行的服務。
// create a thread pool with as many workers as needed
ExecutorService threadPool = Executors.newCachedThreadPool();
// submit your jobs which should implements Runnable
for (YourRunnable job : jobs) {
threadPool.submit(job);
}
提交作業后,關閉服務,等待服務完成,然后您可以查詢作業以獲取相關信息。
// shuts the pool down but the submitted jobs still run
threadPool.shutdown();
// wait for all of the jobs to finish
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// now go back and print out your jobs
for (YourRunnable job : jobs) {
System.out.println(jobs.toString());
}
您可以創建實現Runnable的自定義類,然后編寫這些自定義類的數組。
因此,例如,在您上面編寫的代碼中,您始終可以使用
LittleClass[] objs = new LittleClass[4];
for(int i = 0; i < objs.length; i++) {
objs[i] = new LittleClass();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.