首先申明下,本文为笔者学习《Groovy 程序设计》的笔记,并加入笔者自己的理解和归纳总结。
1、Groovy中,调用Thread的静态方法start来创建线程。
- def printThreadInfo() {
- Thread currentThread = Thread.currentThread()
- println "Current Thread is ${currentThread}"
- }
- printThreadInfo()
- Thread.start {
- printThreadInfo();
- }
Current Thread is Thread[main,5,main]
Current Thread is Thread[Thread-1,5,main]
2、sleep方法可以用来暂停当前操作。
- startTime = System.currentTimeMillis()
- new Object().sleep(2000)
- endTime = System.currentTimeMillis()
- println "Thread last ${endTime - startTime} MilliSeconds"
Thread last 2001 MilliSeconds
3、如果sleep方法返回true,inturrpt方法可以打断sleep。
- def interruptSleep(name, flag) {
- thread = Thread.start(name) {
- startTime = System.currentTimeMillis()
- new Object().sleep(2000) {
- flag
- }
- endTime = System.currentTimeMillis()
- Thread currentThread = Thread.currentThread()
- println "${currentThread} last ${endTime - startTime} MilliSeconds"
- }
- thread.interrupt()
- }
- interruptSleep("thread1", true)
- interruptSleep("thread2", false)
Thread[thread1,5,main] last 2 MilliSeconds
Thread[thread2,5,main] last 2001 MilliSeconds
4、Daemon线程在主线程退出后不再运行。
- Thread.start {
- startTime = System.currentTimeMillis()
- new Object().sleep(2000)
- endTime = System.currentTimeMillis()
- println "Thread last ${endTime - startTime} MilliSeconds"
- }
- Thread.startDaemon {
- startTime = System.currentTimeMillis()
- new Object().sleep(3000)
- endTime = System.currentTimeMillis()
- println "Daemon Thread last ${endTime - startTime} MilliSeconds"
- }
Thread last 2002 MilliSeconds