kotlin 线程基础

1.创建线程

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

val 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()}")
}

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

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()}")
  }
}

可变字段

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

  @Volatile
    private var s = ""

 

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消失
作者:请输入妮称
链接:https://www.jianshu.com/p/a684118c1b98
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值