Kotlin多线程编程

  • Kotlin中没有synchronized、volatile关键字。Kotlin的Any类似于java的Object,但是没有wait()、notify()和notifyAll()方法。
    Kotlin通过封装java中的线程类,简化了我们的编码。同时我们可以使用一些特定的注解,使用java中的同步关键字等。
创建线程

在java中通常有两种方式来创建线程:
扩展Thread类或者进行实例化通过构造函数传入一个Runnable。Kotlin中也可以使用这两种方式

  1. 使用对象表达式创建
object : Thread() {
            override fun run() {
                println("使用对象表达式创建")
            }
        }.start()
  1. 使用Lambda表达式
   Thread {
          println("通过Lambda表达式")
      }.start()
  1. 使用Kotlin封装的Thread()函数
    如下面的方式
val t = Thread() {
            println("thread")
        }
        t.isDaemon = false
        t.name = "tThread"
        t.priority = 3
        t.start()

Kotlin中把上面代码的方式简化了

 val t = thread(start = true, isDaemon = false, name = "thread", priority = 3) {
            println("thread")
        }

实际上Kotlin是把Thread进行了抽象封装

public fun thread(
    start: Boolean = true,
    isDaemon: Boolean = false,
    contextClassLoader: ClassLoader? = null,
    name: String? = null,
    priority: Int = -1,
    block: () -> Unit
): Thread {
    val thread = object : Thread() {
        public override fun run() {
            block()
        }
    }
    if (isDaemon)
        thread.isDaemon = true
    if (priority > 0)
        thread.priority = priority
    if (name != null)
        thread.name = name
    if (contextClassLoader != null)
        thread.contextClassLoader = contextClassLoader
    if (start)
        thread.start()
    return thread
}

同步方法和块

synchronized不是Kotlin关键字,它替换为@Synchronized注解。

@Synchronized
    fun appendText() {
        
    }
可变字段

Kotlin没有volatile关键字但是有@Volatile注解,JVM会标记为Volatile

  @Volatile
    private var s = ""
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值