Java多线程线程池行为

时间:2016-07-26 20:24:23

标签: java multithreading

我正在学习John Purcell的课程中的Java多线程,并对线程池有疑问。我从迄今为止所学到的知识中了解到,多线程中线程的执行时间依赖于硬件处理器。我在John的一个示例中使用了Java多线程中的ExecutorService实用程序,这里是代码。什么是导致这些线程池在不同计算机上以不同方式执行的确切现象?

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

class Processor implements Runnable {

  private int count = 0;

  public Processor (int count){
    this.count = count;
  }

  public void run(){
    System.out.println("Started: " + count);

    try{
        Thread.sleep(5000);
    } catch(InterruptedException ex){
        ex.printStackTrace();
    }

    System.out.println("Completed: " + count);

  }

}

public class Pooling{

  public static void main(String args[]){

    ExecutorService executor = Executors.newFixedThreadPool(2);

    for (int i=0; i<5; i++){
    executor.submit(new Processor(i));
    }

    executor.shutdown();

    System.out.println("All tasks submitted...");

    try{
        executor.awaitTermination(1, TimeUnit.DAYS);
    } catch(InterruptedException ex){
        ex.printStackTrace();
    }

    System.out.println("All tasks have been completed. ");

  }

}

此代码在一台计算机上打印出以下池(Win 7,32位,2M缓存,1.86 GHz)

Started: 0
Started: 1
All tasks submitted...
Completed: 0
Started: 2
Completed: 1
Started: 3
Completed: 3
Started: 4
Completed: 2
Completed: 4
All tasks have been completed. 
BUILD SUCCESSFUL (total time: 16 seconds)

并在另一台计算机上打印以下池(Win 8.1,64位,3M缓存,2.7 GHz)

All tasks submitted...
Started: 1
Started: 0
Completed: 1
Started: 2
Completed: 0
Started: 3
Completed: 2
Started: 4
Completed: 3
Completed: 4
All tasks have been completed. 
BUILD SUCCESSFUL (total time: 16 seconds)

0 个答案:

没有答案