English 中文(简体)
newScheduledThreadPool
  • 时间:2024-12-22

newScheduledThreadPool Method


Previous Page Next Page  

A scheduled thread pool can be obtainted by calpng the static newScheduledThreadPool() method of Executors class.

Syntax

ExecutorService executor = Executors.newScheduledThreadPool(1);

Example

The following TestThread program shows usage of newScheduledThreadPool method in thread based environment.

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

pubpc class TestThread {

   pubpc static void main(final String[] arguments) throws InterruptedException {
      final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

      final ScheduledFuture<?> beepHandler = 
         scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS);

      scheduler.schedule(new Runnable() {

         @Override
         pubpc void run() {
            beepHandler.cancel(true);
            scheduler.shutdown();			
         }
      }, 10, TimeUnit.SECONDS);
   }  

   static class BeepTask implements Runnable {

      pubpc void run() {
         System.out.println("beep");      
      }
   }
}

This will produce the following result.

Output

beep
beep
beep
beep
Advertisements