kotlin 线程基础

作者: 请输入妮称 | 来源:发表于2018-07-24 18:57 被阅读29次

    1.创建线程

    在 kotlin中,有三种方式可以创建线程
    1.继承Thread类

    object : Thread() {
      override fun run() {
        println("running from Thread: ${Thread.currentThread()}")
      }
    }.start()
    

    2.使用Runnable类初始化Thread对象。

    Thread({
      println("running from lambda: ${Thread.currentThread()}")
    }).start()
    

    这里我们并没有看到,Runnable对象。其实是被lambda表达式替换了。

    3.使用kotlin提供的封装方法

    thread(start = true) {
      println("running from thread(): ${Thread.currentThread()}")
    }
    

    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中,给方法加锁一般是使用synchronized关键字,但是在kotlin中,并没有这个关键字,取而代之的是@Synchronized注解。

    @Synchronized fun synchronizedMethod() {
      println("inside a synchronized method: ${Thread.currentThread()}")
    }
    

    如果是给代码块加锁,则使用synchronized()方法

    fun methodWithSynchronizedBlock() {
      println("outside of a synchronized block: ${Thread.currentThread()}")
      synchronized(this) {
        println("inside a synchronized block: ${Thread.currentThread()}")
      }
    }
    

    3.wait(), notify() and notifyAll()

    kotlin的基类是Any,类似于java中的Object,但是没有提供wait()、notify()、notifyAll()方法。但是我们依然可以通过创建Object的实例,从而调用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()
    }
    

    4.线程相关第三方库

    kotlin并不打算在语言层面对线程方面做过多的设计,而是将其转嫁到第三方库上。

    1.Kovenant library
    kotlin中的promise。

    2.Quasar library
    暂时没有研究,有兴趣可自行观看,轻量级的线程和协程实现

    5.当inline遇到synchronized

    这里存在一些问题,当inline修饰的方法加入@Synchronized注解后,那么当inline方法被调用的时候,synchronized锁机制将会消失。

    class AA {
        companion object {
            private var str = "test"
            @JvmStatic
            fun main(args: Array<String>?) {
                synchronizedAnnotationMethod()
            }
    
            private @Synchronized
            inline fun synchronizedAnnotationMethod() {
                print(str)
            }
        }
    }
    

    反编译后的代码

        @JvmStatic
        public final void main(@Nullable String[] args) {
            AA.Companion this_$iv = this;
            Object object = this_$iv.getStr();
            System.out.print(object);
        }
    
        private final synchronized void synchronizedAnnotationMethod() {
            String string = this.getStr();
            System.out.print((Object)string);
        }
    

    可以看到内联之后,synchronized消失

    相关文章

      网友评论

        本文标题:kotlin 线程基础

        本文链接:https://www.haomeiwen.com/subject/eoyymftx.html