Thread Sleep Method in Scala
First, this article will learn how Threads are implemented in Scala. Then, we will see how the Sleep method works in Scala.
Threads in Scala
Threads are lightweight sub-processes that take less space and run faster. In a multi-threaded environment, many threads run concurrently, each performing a different task. This leads to better CPU utilization and resources, and in turn, we get better throughput.
In Scala, threads are created in two ways: First, is Extending the Runnable
Interface, and the second is Extending the Thread
class.
Method 1: Extending Runnable Interface
We create a class that extends the Runnable interface and override the run() method.
Example code:
class test extends Runnable
{
override def run()
{
println("Thread "+Thread.currentThread().getName()+" is running.")
}
}
object MyClass {
def main(args: Array[String]) {
for(i<- 1 to 5)
{
var obj = new Thread(new test()) //creating the object
obj.setName(i.toString())
obj.start() //starts the thread
}
}
}
Output:
Thread 1 is running.
Thread 2 is running.
Thread 3 is running.
Thread 4 is running.
Thread 5 is running.
Method 2: Extending Thread
Class
We create a class that extends the Thread class and override the run()
method.
Example code:
class test extends Thread
{
override def run()
{
println("Thread "+Thread.currentThread().getName()+" is running.")
}
}
object MyClass {
def main(args: Array[String]) {
for(i<- 1 to 5)
{
var obj = new Thread(new test()) //creating the object
obj.setName(i.toString())
obj.start() //starts the thread
}
}
}
Output:
Thread 1 is running.
Thread 2 is running.
Thread 3 is running.
Thread 4 is running.
Thread 5 is running.
Thread.sleep()
in Scala
Thread.sleep(time)
is used to sleep a thread for some specific amount of time. Time in milliseconds is passed to it as an argument.
Syntax:
Thread.sleep(1000)
Here the thread would sleep for 1000 milliseconds
Example code :
class test extends Thread
{
override def run()
{
var i = 0
println("Thread "+Thread.currentThread().getName()+" is running.")
for(i<-1 to 5)
{
Thread.sleep(1000) //will sleep the thread
}
}
}
object MyClass {
def main(args: Array[String]) {
for(i<- 1 to 5)
{
var obj = new Thread(new test()) //creating the object
var thread1 = new Thread(obj);
var thread2 = new Thread(obj);
thread1.setName("1")
thread2.setName("2")
thread1.start() //starts the thread
thread2.start()
}
}
}
Output:
Thread 1 is running.
Thread 2 is running.
Thread 1 is running.
Thread 2 is running.
Thread 1 is running.
Thread 2 is running.
Thread 1 is running.
Thread 2 is running.
Thread 1 is running.
Thread 2 is running.