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

本文介绍了Groovy中sleep方法的基本用法及示例,包括单线程和多线程环境下的应用。sleep方法可以引入指定毫秒数的延迟,帮助实现简单的定时任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自: 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

转载于:https://www.cnblogs.com/z1500592/p/6015483.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值