簡體   English   中英

Java並發時間性能:執行器,線程組還是可運行的?

[英]Java Concurrency Time Performance: Executors, ThreadGroup or Runnable?

我開始為Java中已經存在的項目(非多線程項目)開發一些多線程平台,並且我需要性能GAIN,以減少整個項目中復雜計算的時間。

我一直在使用Executors,但我真的不知道與ThreadGroup或純Runnable相比,它是否是提高性能的最佳解決方案。

那么,應該使用哪一個呢?

如果將線程池重復用於多個計算(即,您啟動具有10個線程的池並執行10次任務100次,而不是每次100次啟動10個線程),則只會從線程池中獲得性能提升。 他們仍然要花一些初始費用才能啟動,您無法逃脫這一部分。 所以這是一個例子:

ExecutorService exec = Executors.newFixedThreadPool(10);

for(int i = 0; i < 10; i++) {
    exec.submit(new Task(i));
}    

// later

for(int i = 0; i < 10; i++) {
    exec.submit(new Task(i));
}    

exec.shutdown(); // etc.

在這種情況下,我一開始只支付啟動10個線程的開銷。

使用純線程:

List<Thread> threads = new ArrayList<Thread>();
for(int i = 0; i < 10; i++) {
    Thread t = new Thread(new Task(i));
    threads.add(t);       
    t.start();   
}  

for(Thread t: threads) {
    t.join();
}

// later I need more work

threads = new ArrayList<Thread>();
for(int i = 0; i < 10; i++) {
    Thread t = new Thread(new Task(i));
    threads.add(t);        
    t.start();  
}  

for(Thread t: threads) {
    t.join();
}

在這種情況下,我要支付兩次啟動10個線程的開銷,這是線程的一種不好用法。 當然,如果您只需要執行一次這些任務,那么性能就不會有任何區別,除了與執行者一起工作更容易。

我沒有理解純Runnable (也許是純線程?)的含義,因為線程池(執行程序)也可以在Runnable工作。

ThreadGroup是組織線程的一種方式,很少使用。

Executors采用“純” Runnable所以我認為您打算將Executors與分叉自己的線程進行比較? 就性能增益而言,這兩種解決方案都是相似的,但是ExecutorService類非常易於使用。 它們允許你提交了一系列Runnable的是並行取決於你有多少線程給泳池執行類。

真正的訣竅是弄清楚將您的工作划分為可以並行執行的作業-在分叉的線程中或通過線程池。

Executors常見的代碼模式:

// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// or you can create an open-ended thread pool
// ExecutorService threadPool = Executors.newCachedThreadPool();
// submit my jobs which are classes that implement Runnable
for (MyRunnable myRunnable : myRunnables) {
   threadPool.submit(myRunnable);
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM