Some Groovy Threading

There is an example of using threads with Groovy in Venkat’s book.

He uses the GDK extension to Thread and calls Thread.start. I wondered if the main thread would wait until the started thread completed, and what would happen if you started another thread.

I made some changes, and ran it.

Here is my class:

package info.shelfunit.venkat.ch07

class BetterThreadExample {
    
    def printThreadInfo( msg ) {
        println "$msg" 
    }
    
    def doStuff() {
        sleep( 5000 )
        printThreadInfo 'Main'
        println "Main is ${Thread.currentThread().name}"
        Thread.start {
            def name = Thread.currentThread().name
            printThreadInfo "AA Started: ${name}"
            sleep( 3000 ) 
            println "AA Interrupted 1" 
            sleep( 1000 )
            println "AA IN started"
            sleep( 3000 )
            println "AA still in started"
            println "AA Finished Started"
        }
        
        Thread.start( 'Second' ) {
            def name = Thread.currentThread().name
            printThreadInfo "BB Started Daemon: ${name}"
            sleep( 5000 ) 
            println "BB Interrupted 2" 
            sleep( 1000 )
            println "BB in second thread"
            sleep( 1000 )
            println "BB Finished Started Daemon"
        }
        println "At the end in main"
    }
      static void main( String[] args ) { 
          def bte = new BetterThreadExample()
          bte.doStuff()
      } // end method main

}

Here is the result:

Main
Main is main
At the end in main
AA Started: Thread-1
BB Started Daemon: Second
AA Interrupted 1
AA IN started
BB Interrupted 2
BB in second thread
BB Finished Started Daemon
AA still in started
AA Finished Started

 

So the main thread gets to its last statement pretty quickly. The two threads run simultaneously. I already knew this, but it’s good to review threads every now and then.

I was always intimidated by threading and concurrent  programming. Maybe it’s not too bad in Groovy.

You’re welcome.

Image from Aurora Consurgens, a 15th century manuscript housed at Central Library of Zurich. Image from e-Codices. This image is assumed to be allowed under Fair Use.