迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 >

Scala 中的线程休眠方法

作者:迹忆客 最近更新:2023/03/24 浏览次数:

首先,本文将学习如何在 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.

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Scala 中的同步

发布时间:2023/03/24 浏览次数:153 分类:编程语言

在本教程中,我们将介绍同步并演示如何在 Scala 语言中使用同步。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便