2017-10-17 265 views
-2

代碼:的Java ScheduledExecutorService的給奇怪的結果

import java.util.concurrent.Executors; 
import java.util.concurrent.ScheduledExecutorService; 
import java.util.concurrent.TimeUnit; 

public class Test implements Runnable { 

    private Integer xyz = 1; 

    public static void main(String[] args) throws InterruptedException { 
     ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); 

     Test test = new Test(); 
     test.xyz = 20; 

     Test test2 = new Test(); 

     System.out.println("Values of xyz = " + test.xyz + " , " + test2.xyz); 

     executorService.scheduleWithFixedDelay(test, 100, 1000, TimeUnit.MILLISECONDS); 
     executorService.scheduleWithFixedDelay(test2, 100, 100, TimeUnit.MILLISECONDS); 
     executorService.awaitTermination(3000, TimeUnit.MILLISECONDS); 
     executorService.shutdown(); 
    } 

    @Override 
    public void run() { 
     this.xyz += (int) Thread.currentThread().getId(); 
     System.out.println(Thread.currentThread().getId() + " " + this.xyz); 
    } 
} 

輸出:

Values of xyz = 
20 1 | 
10 30 | 
11 12 | 
11 23 | 
11 34 | 
11 45 | 
11 56 | 
11 67 | 
11 78 | 
11 89 | 
11 100 | 
11 111 | 
10 40 | 
11 122 | 
11 133 | 
11 144 | 
11 155 | 
11 166 | 
11 177 | 
11 188 | 
11 199 | 
11 210 | 
11 221 | 
10 50 | 
11 232 | 
11 243 | 
11 254 | 
11 265 | 
10 275 | (10 should have been 60 here) 
10 285 | 
10 295 | 
10 305 | 
10 315 | 
+3

'test'運行3次,'test2'在2個不同的線程上執行。那裏沒有什麼令人驚訝的。你爲什麼期望60? – assylias

+0

我錯過了一些關於ScheduledExecutorService的上下文,我想不。的任務等於沒有。 threadPool大小。不知道他們是在多個線程中執行以滿足費率要求。 - 謝謝 –

回答

1

ScheduledExecutorService的使用分配給運行在指定的速度提交的任務線程。誤解是每個線程都與1個任務相關聯,僅用於以指定的頻率運行該特定任務。但事實並非如此,所以這是有道理的。