2014-12-02 55 views
0

我有一個方法可以將素數從1計數到x,並且當x是一個非常大的數字(例如1000000000)時,我想要在線程之間拆分工作。我的素數計數器接受1個參數x,這是檢查它是否爲素數的最後一個數字。此方法返回計數方法計算的素數整數。我知道,我能有這樣的:在參數範圍內的線程之間拆分工作

Thread thread1 = new Thread(new Runnable() { 

     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      int primes = primeCounter(1000000); 
      System.out.println("There are: " + primes+ " primes in betweem 1 and " + 1000000); 

     } 
    }); 

但我如何從百萬繼續到100000000另一個線程,並加入這兩個線程?

+0

你可以改變你的primeCounter也接受較低的樂隊? – Lrrr 2014-12-02 22:01:11

回答

1

首先,像評論中提到的那樣,改變你的primepounter,以便ist接受一個範圍。 其次,創建一個類繼承Thread,如:

class MyThread extends Thread { 
    long start; 
    long stop; 
    int primes = 0; 

    MyThread(long start, long stop) { 
     this.start = start; 
     this.stop = stop; 
    } 

    @Override 
    public void run() { 
     primes = primeCounter(start, stop); 
     System.out.println("There are: " + primes + " primes in betweem " + start + " and " + stop); 
    } 

    private int primeCounter(long start, long stop) { 
     int counter = 0; 
     //..... 
     return counter; 
    } 
} 

然後你就可以創建線程,啓動它們,等到他們都完成了:

long max = 1000000000; 
    long packetSize = 1000000; 
    List<MyThread> threads = new ArrayList<>(); 
    long start = 0; 
    for (int i = 0; i < (int) (max/packetSize); i++) { 
     threads.add(new MyThread(start, start = start + packetSize)); 
    } 
    threads.forEach((Thread t)-> t.start()); 
    threads.forEach((Thread t)-> { try {t.join();}catch(InterruptedException e) {throw new RuntimeException(e);}}); 

的例子是非常簡單的,變化它符合你的需求,不要忘記異常處理:)