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.