Kotlin 并发

2019-05-23  本文已影响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 的实现
更多并发的实现方式

上一篇 下一篇

猜你喜欢

热点阅读