简体   繁体   中英

Java: How to make a new thread every second

I have a thread in Java that makes a web call and stores the information retrieved, but it only retrieves information for that particular instant. I'd like to run this thread every second for a certain period of time to get a better view of the data. How can I do this? I've looked at ScheduledExecutorService, and from what I can tell if the thread is still running when it's time to set up the next run, it waits until the first thread is complete, which isn't what I'm looking for.

What you need is the scheduleAtFixedRate method: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRate(java.lang.Runnable,%20long,%20long,%20java.util.concurrent.TimeUnit)

When the scheduler waits until the first thread is complete, it's because you're using scheduleWithFixedDelay.

However, if you absolutely want the threads run concurrently, you should try this:

    pool.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            pool.submit(myJob);
        }
    }, 1, 1, TimeUnit.SECONDS);

I advise to always use a pool.

You can do this by a double schedule. Use scheduleWithFixedDelay() to set off a job every second. This job starts the method which you really want to run. Here is some code based on Oracle's ScheduledExecutorService API.

The Thread.sleep() is there to simulate a long-running task.

class Beeper {
   public static void main(String[] args) {
      (new Beeper()).beep();
   }
   private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

   public void beep() {
       final Runnable beeper = new Runnable() {
           public void run() { 
               System.out.println("beep"); 
               try {
                   Thread.sleep(10000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       };
       final Runnable beeper2 = new Runnable() {
           public void run() {
               (new Thread(beeper)).start();
           }
       };
       final ScheduledFuture<?> beeperHandle =       scheduler.scheduleAtFixedRate(beeper2, 1, 1, SECONDS);
    }
 }

What about this?

 public static void main (String [] args) throws InterruptedException{

ExecutorService executorService =
        Executors.newFixedThreadPool(10);

while (true){
    executorService.submit(new Runnable() {
        @Override
        public void run() {
            // do your work here..
            System.out.println("Executed!");    

        }});
    Thread.sleep(1000);
    }       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM