张培秋 发表于 2012-4-12 19:56:22

八维学教会您【JAVA5线程池】使用

八维学院提供以下线程池:缓存线程池(newCachedThreadPool),可以创建任意个线程,每个任务过来后都会创建一个线程,用于任务少,或执行时间 短的任务,例如我们创建十个任务,那么缓冲线程池将会创建十个线程来执行。如下代码: view plaincopy ExecutorService threadPool =Executors.newCachedThreadPool();

  for(int i=1; i<=10; i++){ final int taskId =i;threadPool.execute(new Runnable(){

  public void run() { for(int i=1; i<=10; i++){System.out.println(Thread.currentThread()。getName() +" is looping of " + i + " the task is " + taskId);try {Thread.sleep(20);} catch (InterruptedException e) { // TODO Auto-generatedcatch block e.printStackTrace();}

  }

  });} System.out.println("add all of 10task");threadPool.shutdown();固定数量线程池(newFixedThreadPool)允许我们创建固定线程数量的线程池,如果任务数大于线程池中线程的数量,那么任务将等待,如下代码: view plaincopyExecutorService threadPool = Executors.newFixedThreadPool(3);for(int i=1;i<=10; i++){ final int taskId = i;threadPool.execute(new Runnable(){

  public void run() { for(int i=1; i<=10; i++){System.out.println(Thread.currentThread()。getName() +" is looping of " + i + " the task is " + taskId);try {Thread.sleep(20);} catch (InterruptedException e) { // TODO Auto-generatedcatch block e.printStackTrace();}

  }

  });} System.out.println("add all of 10task");threadPool.shutdown();如何实现线程挂掉后重新启动(创建单一的线程池)newSingleThreadExecutor(),这样线程池中只会有一个线程工作,当线程失败后会重新创建一个线程将失败的线程替换掉定时器线程池(scheduleAtFixedRate)与定时器很类似,可以指定线程池中线程在多长时间后执行,以及每个多长时间执行一次,代码如下,可以模拟让炸弹在6s后爆炸,并且每个2s炸一次: view plaincopy Executors.newScheduledThreadPool(3)。scheduleAtFixedRate(// .schedule(new Runnable(){

  public void run() { System.out.println("boming");}

  }, 6, 2, TimeUnit.SECONDS);}

  大家可以执行代码测试。

平安 发表于 2012-4-12 20:25:45

{:39:}{:39:}
页: [1]
查看完整版本: 八维学教会您【JAVA5线程池】使用