2017-05-09 110 views
1

我想使用不同的線程從共享的整數列表中刪除值。爲此,我決定使用ThreadPoolExecutor服務。Java ThreadPoolExecutor未創建新線程?

首先,我創建了一個BlockingQueue來存儲100萬個值。

BlockingQueue q = new LinkedBlockingQueue<Integer>(); 
    for (int i=0;i<100000;i++) 
     q.add(i); 

其次,我的ThreadPoolExecutor

ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); 
MyExecutorJob job = new MyExecutorJob(q); 
executor.execute(job); 

作業類的主體是這樣的:

public class MyExecutorJob extends Thread 
{ 
    private BlockingQueue<Integer> queue; 

    public MyExecutorJob(BlockingQueue<Integer> queue) 
    { 
    this.queue = queue; 
    } 

    @Override 
    public void run() 
    { 
     try 
     { 
      while (!queue.isEmpty()) 
      { 
       Integer x = (Integer) queue.take(); 
       System.out.println(x + " - " + this.getName()); 
      } 
     } 
     catch (Exception ex) 
     { 
     } 

    } 
} 

結果總是

1 - Thread-0 
2 - Thread-0 
3 - Thread-0 
4 - Thread-0 
.... 
100000 - Thread-0 

它看起來像我的工作沒有被兩個線程執行秒。它始終是相同的線程。 我需要使用兩個線程遍歷整數值列表。

我在做什麼錯?有什麼我沒看到?

謝謝!

+1

你真的'submit'以上的工作實例? – Thilo

+1

您只向ThreadProoolExecutor提交了一個作業。這項工作只能傳給一個線程。嘗試再次調用''executor.execute(job);''。 – f1sh

+1

另請注意,'this.getName()'與執行此代碼的線程的名稱完全無關。爲此使用'Thread.currentThread()。getName()'。它會像'pool-0-thread-0'一樣。你不應該讓你的工作類擴展Thread。改爲實現Runnable或Callable。否則,你只會迷惑自己。 – Thilo

回答

2

1.錯誤爲this.getName(),請使用Thread.currentThread().getName();

2.你已經初始化了一個線程池,它有兩個線程,但你只有一個工作,那麼線程池將只提供一個線程來執行你的工作;

0

嘗試這種方式,但測試與100替換100000

public static void main(String[] args) { 
    ExecutorService executor = Executors.newFixedThreadPool(2); 
    IntStream.range(0, 100000).forEach(i -> 
     executor.execute(() -> System.out.println(i + " - " + currentThread().getName()))); 
} 
相關問題