Creating a Thread (and Runnable) in Scala

I ran into a strange problem this weekend where I noticed a huge difference between the way a Scala Future and a Thread worked for the exact same code. I think I’m pretty aware of the obvious differences between futures and threads, so this really caught me by surprise. If/when I figure out why there was such a difference in behavior for the given problem I’ll post that information here.

A Scala Thread example

While that problem will haunt me indefinitely, what I really want to post here today is a simple Scala Thread example:

// scala thread example
for (i <- 1 to 100) {
    val thread = new Thread {
        override def run {
            // your custom behavior here
        }
    }
    thread.start
    Thread.sleep(50) // slow the loop down a bit
}

As you can see, creating a Thread in Scala is just like creating a Thread in Java, with a few slight syntactical differences. The most important parts are to define your custom behavior in the run method, and to call start when you’re ready to start your thread.

A Scala Runnable example

Of course you can also use a Runnable to create a Thread. I just typed the following code here and haven’t tested it, but a similar Runnable example will look something like this:

// define a scala runnable
class MyThread extends Runnable {

    def run {
        // your custom behavior here
    }

}

// start your runnable thread somewhere later in the code
new Thread(new MyThread)).start

Thread and Runnable resources

See the following links for good Java Thread and Runnable examples, which can easily be converted to Scala:

As mentioned, if I ever figure out why a Future and a Thread behaved so differently for my problem, I’ll post that information here.