zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    常用网址记录
    css一些兼容问题
    css hack
    js 闭包
    js 继承
    js 实现淘宝放大镜
    css做三角形的方法
    js 轮播效果
    css3特效
    css布局
  • 原文地址:https://www.cnblogs.com/z1500592/p/6015483.html
Copyright © 2011-2022 走看看