Groovy Sleep Examples (by default, sleep is single thread)

转自: http://grails.asia/groovy-sleep-examples

A very common thing we encounter when programming scripts is introducing delays or sleep between statements. In Groovy, sleep method can be used to perform simple delays. Below are some examples.

Syntax

Here is the syntax for Groovy Sleep

static void sleep(long milliseconds)

Notice that the parameter is the amount of time in milliseconds to delay the execution of the thread.

Groovy Sleep Single Thread Example

Here is a simple example of using Groovy sleep on a single thread. Note that we can invoke sleep from static main method - meaning it is also a static method. The sleep method delays the current thread.

class TestSleep {
   static void main(String[] args) {          
      println 'Step 1'
      sleep(3000)
      println 'Step 2'
      sleep(3000)
      println 'Step 3'
   }
}

Here is the output.

Step 1
Step 2
Step 3

As expected, a delay of 3 seconds is induced between each line printed.

Groovy Sleep Multi Thread Example

The sleep method delays the current thread it is into. Here is a simple multi-threaded Groovy sleep example.

class TestMultiThreadSleep implements Runnable {
   String name;
   public TestMultiThreadSleep(String name) {
      this.name = name;
   }
   static void main(String[] args) {
      Thread thread1 = new Thread(new TestMultiThreadSleep("A"));          
      Thread thread2 = new Thread(new TestMultiThreadSleep("B"));
      Thread thread3 = new Thread(new TestMultiThreadSleep("C"));
      thread1.start();
      thread2.start();
      thread3.start();
    }
   @Override
   public void run() {
      println "${name} Step 1"
      sleep(3000)
      println "${name} Step 2"
      sleep(3000)
      println "${name} Step 3"      
   }
}

Here is a sample output. The sleep only affects the thread it is into as shown below.

A Step 1
C Step 1
B Step 1
A Step 2
B Step 2
C Step 2
A Step 3
C Step 3
B Step 3