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
  • 相关阅读:
    微信小程序之相对位置
    SQL中 in 、not in 、exists、not exists 用法和差别
    指令打印程序(通过Socket)
    javaee正则表达式基础和常用表达式
    分析JSON/XML
    Hello2 source analisis(代码分析)
    Analysis Of HTTP
    Servlet Filter详细讲
    Analysis of Web.xml in Hello1 project
    Java annotation (注解)
  • 原文地址:https://www.cnblogs.com/z1500592/p/6015483.html
Copyright © 2011-2022 走看看