kotlin_基础_并发

22 篇文章 0 订阅

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

1, 创建线程

    // 方法一
    object : Thread() {  
      override fun run() {
        println("running from Thread: ${Thread.currentThread()}")
      }
    }.start()
    
    // 方法二
    Thread({  
      println("running from lambda: ${Thread.currentThread()}")
    }).start()

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
    }

2, 同步方法和语句块

// 这里 类似于 Java 的 synchroize 关键字,只是这里替换为了注释的方式
    @Synchronized fun synchronizedMethod() {
      println("inside a synchronized method: ${Thread.currentThread()}")
    }
    

    // 语句块与java 的用法类似,但原理是不一样的
    fun methodWithSynchronizedBlock() {  
      println("outside of a synchronized block: ${Thread.currentThread()}")
      synchronized(this) {
        println("inside a synchronized block: ${Thread.currentThread()}")
      }
    }
    // synchronized 定义
    @kotlin.internal.InlineOnly
    public actual inline fun <R> synchronized(lock: Any, block: () -> R): R {
        contract {
            callsInPlace(block, InvocationKind.EXACTLY_ONCE)
        }
    
        @Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE", "INVISIBLE_MEMBER")
        monitorEnter(lock)
        try {
            return block()
        }
        finally {
            @Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE", "INVISIBLE_MEMBER")
            monitorExit(lock)
        }
    }

3,volatile 用法

    @Volatile private var running = false
    
    fun start() { 
        running = true 
        thread(start = true) {
            while(running) {
                println("Still running:${Thread.currentThread()}")
            }
        }
    }
    
    fun stop() {
        running = false 
        println("Stopped:${Thread.currentThread()}")
    }

定义

    @Target(FIELD)
    @Retention(AnnotationRetention.SOURCE)
    @MustBeDocumented
    public actual annotation class Volatile
    
    /**
     * Marks the JVM backing field of the annotated property as `transient`, meaning that it is not
     * part of the default serialized form of the object.
     */
    @Target(FIELD)
    @Retention(AnnotationRetention.SOURCE)
    @MustBeDocumented
    public actual annotation class Transient
    
    /**
     * Marks the JVM method generated from the annotated function as `strictfp`, meaning that the precision
     * of floating point operations performed inside the method needs to be restricted in order to
     * achieve better portability.
     */
    @Target(FUNCTION, CONSTRUCTOR, PROPERTY_GETTER, PROPERTY_SETTER, CLASS)
    @Retention(AnnotationRetention.SOURCE)
    @MustBeDocumented
    public actual annotation class Strictfp
    
    /**
     * Marks the JVM method generated from the annotated function as `synchronized`, meaning that the method
     * will be protected from concurrent execution by multiple threads by the monitor of the instance (or,
     * for static methods, the class) on which the method is defined.
     */
    @Target(FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER)
    @Retention(AnnotationRetention.SOURCE)
    @MustBeDocumented
    public actual annotation class Synchronized

4,wait,notify 与 notifyAll

    private val lock = java.lang.Object()
    
    fun produce() = synchronized(lock) {
      while (items >= maxItems) {
        lock.wait()
      }
      Thread.sleep(rand.nextInt(100).toLong())
      items++
      println("Produced, count is $items: ${Thread.currentThread()}")
      lock.notifyAll()
    }
    
    fun consume() = synchronized(lock) {
      while (items <= 0) {
        lock.wait()
      }
      Thread.sleep(rand.nextInt(100).toLong())
      items--
      println("Consumed, count is $items: ${Thread.currentThread()}")
      lock.notifyAll()
    }

这里其实用的是黑科技,直接用的 java 的实现
更多并发的实现方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值