Kotlin 多线程(1)

Kotlin通过封装Java的线程类,简化了线程操作。
可以使用特定的注解,直接使用Java的同步关键字等。

Kotlin中没有 synchronized、volatile关键字;
Kotlin的Any类似于Java的Object,但是没有 wait()、notify()、notifyAll() 方法。

创建线程

  1. 使用对象表达式创建线程
  2. 使用Lambda表达式创建线程
  3. 使用Kotlin封装的 thread() 函数创建线程
		// object 对象表达式,创建一个匿名类,并重写 run() 方法
    object : Thread() {
        override fun run() {
            sleep(200)
            val line = currentThread()
            println("使用 Thread 对象表达式: $line")
            // 输出:使用 Thread 对象表达式: Thread[Thread-0,5,main]
        }
    }.start()
    // 使用Lambda表达式,将Runnable对象传给新创建的Thread对象
    val t0 = Thread {
        Thread.sleep(800)
        val line = Thread.currentThread()
        println("使用Lambda表达式: $line")
        // 输出:使用Lambda表达式: Thread[myThread,3,main]
    }

    t0.isDaemon = false
    t0.name = "myThread"
    t0.priority = 3
    t0.start()

Kotlin将这样的操作 封装简化(简化了样板代码):

    // 使用Kotlin封装的 thread() 函数创建线程
    thread(start = true, isDaemon = false, name = "myThread_x",priority = 3) {
        Thread.sleep(1000)
        val line = Thread.currentThread()
        println("使用Kotlin封装的 thread() 函数: $line")
        // 输出:使用Kotlin封装的 thread() 函数: Thread[myThread_x,3,main]
    }

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 注解,将方法标记为同步,
 * 作用和Java的 synchronized 关键字相同。
 */
@Synchronized
fun appendFileBytesF(array: ByteArray, destFile: String): Unit {
    val f = File(destFile)
    if (!f.exists()) {
        f.createNewFile()
    }
    f.appendBytes(array)
}
/**
 * 使用 synchronized() 函数,同步代码块
 * 锁是该函数的参数
 */
fun appendFileBytesSync(array: ByteArray, destFile: String): Unit {
    val f = File(destFile)
    if (!f.exists()) {
        f.createNewFile()
    }
    synchronized(mLock) {f.appendBytes(array)}
}

可变字段

Kotlin中没有 volatile 关键字,但是有 @Volatile 注解

// 注解@Volatile 会将JVM备份字段标记为 volatile
@Volatile private var running = false

fun tStart(): Unit {
    running = true
    thread(start = true) {
        var count = 0
        while (running) {
            Thread.sleep(100)
            count++
            val line = Thread.currentThread()
            println("running: $line {$count}")
        }
    }
}

fun tStop(): Unit {
    running = false
    val line = Thread.currentThread()
    println("stopped: $line")
}

// 测试
fun testVolatile(): Unit {
    thread(start = true) {
        tStart()
        Thread.sleep(1200)
        tStop()
    }
}

Kotlin中还有更好用的 协程并发库

  • 11
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Kotlin 是一种基于 JVM 的编程语言,因此它可以使用 Java 提供的多线程 API 实现多线程。除此之外,Kotlin 也提供了一些方便的语法糖来简化多线程编程。 下面是使用 Kotlin 实现多线程的步骤: 1. 创建一个继承自 Thread 的线程类,重写 run() 方法,在该方法中编写线程执行的代码。 2. 在主线程中创建该线程的实例,并调用 start() 方法启动该线程。 3. 如果需要在子线程中更新 UI,需要使用 Handler 或者 runOnUiThread() 方法。 举个例子,下面是一个简单的多线程实现代码: ```kotlin class MyThread : Thread() { override fun run() { super.run() // 子线程执行的代码 Log.d("MyThread", "子线程执行中...") } } ``` 然后在主线程中创建该线程的实例并启动: ```kotlin val myThread = MyThread() myThread.start() ``` 除了使用 Java多线程 API,Kotlin 还提供了一些方便的语法糖,例如使用协程来简化异步编程。使用协程,可以在代码中使用类似于同步代码的方式来编写异步任务,这样可以避免回调地狱的问题。 举个例子,下面是使用协程实现多线程的代码: ```kotlin GlobalScope.launch { // 子线程执行的代码 Log.d("MyCoroutine", "子线程执行中...") } ``` 在上面的代码中,使用 `GlobalScope.launch` 可以创建一个新的协程,并在其中编写子线程执行的代码。需要注意的是,在使用协程时需要避免出现线程安全问题,例如避免在不同的协程中同时修改同一个变量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值