簡體   English   中英

Java中的for循環如何讓多個線程同時運行?

[英]How to make multiple Threads run at the same time using a for loop in Java?

我對 java 很陌生,並開始構建一個小程序來查找給定范圍內的素數。 現在我嘗試實現多任務處理,例如將要檢查的數字分成應獨立檢查的 n 個部分。 我想讓它盡可能靈活,所以我沒有在代碼中指定線程數,而是使用了一個提示變量。 現在,代碼可以工作,但線程不能並行運行。

這里似乎有什么問題?

           [...]     
           System.out.println("How many Threads shall be used?");
           int b1 = scan.nextInt();
           scan.close();
           for (int i = 1; i <= b1; i++) {
             long u = (q/b1)*(i-1);
             long o = (q/b1)*i;
             System.out.println("Thread "+i+" started.");
             Thread t1 = new Thread(new thread1 (u, o, i));
             t1.start();
           }


class thread1 implements Runnable{
    public thread1 (long a, long b, int c) {
//a= min. number, b = max. number, c=number of Thread
        primefinder.findPrimes(b,a, c);
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
    }
}

從 javadochttps://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

class PrimeRun implements Runnable {
         long minPrime;
         PrimeRun(long minPrime) {
             this.minPrime = minPrime;
         }

         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }
    

您的邏輯必須在 run() 方法中。 正是這個方法將被調用並在另一個線程上運行。 使用您的實際代碼,您可以在 Runnable 的構造函數中進行計算,該構造函數在您的 for 循環中調用,因此是順序的。

將您的計算移至運行方法將解決問題。

正如Daniel 的正確答案所說,您需要將業務邏輯移動到Runnablerun方法或Callablecall方法中。

此外,在現代 Java 中,我們很少直接處理Thread class。 而是使用 Executors 框架。

ExecutorService es = Executors.newFixedThreadPool( x ) ;
for( … ) { es.submit( task ) ; }
es.shutdown() ;
es.awaitTermination( … ) ;

這已經在 Stack Overflow 上討論過很多次了。 因此,搜索以了解更多信息。

暫無
暫無

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

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