Scala 中的執行緒休眠方法
Suraj P
2023年1月30日
首先,本文將學習如何在 Scala 中實現執行緒。然後,我們將看到 Sleep 方法在 Scala 中是如何工作的。
Scala 中的執行緒
執行緒是輕量級的子程序,佔用的空間更少,執行速度更快。在多執行緒環境中,許多執行緒同時執行,每個執行緒執行不同的任務。這會帶來更好的 CPU 利用率和資源,進而獲得更好的吞吐量。
在 Scala 中,執行緒的建立方式有兩種:一是擴充套件 Runnable
介面,二是擴充套件 Thread
類。
方法一:擴充套件 Runnable 介面
我們建立一個擴充套件 Runnable 介面並覆蓋 run() 方法的類。
示例程式碼:
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
}
}
}
輸出:
Thread 1 is running.
Thread 2 is running.
Thread 3 is running.
Thread 4 is running.
Thread 5 is running.
方法 2:擴充套件 Thread
類
我們建立一個擴充套件 Thread 類並覆蓋 run()
方法的類。
示例程式碼:
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
}
}
}
輸出:
Thread 1 is running.
Thread 2 is running.
Thread 3 is running.
Thread 4 is running.
Thread 5 is running.
Scala 中的 Thread.sleep()
Thread.sleep(time)
用於讓執行緒休眠一段時間。以毫秒為單位的時間作為引數傳遞給它。
語法:
Thread.sleep(1000)
Here the thread would sleep for 1000 milliseconds
示例程式碼:
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()
}
}
}
輸出:
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.