icode icode
首页
  • Android学习

    • 📁基础内容
    • 📺AndroidCore
    • 🎨Android-UI
    • 🏖️Components
    • 📊Fragment
    • 🔗网络操作
    • 🔏异步机制
    • 📦数据存储
    • 🗃️Gradle
  • 学习笔记

    • 『框架』笔记
    • 『Kotlin』笔记
    • 《Vue》笔记
    • 《Git》学习笔记
    • 『Bug踩坑记录』
  • ListView
  • RecyclerView
  • ViewPager
  • Java笔记

    • 🟠JavaSE
    • 🟢JavaWeb
    • 🔴JavaEE
    • ⚪JavaTopic
    • 🍳设计模式
  • 计算机基础

    • 📌计算机网络
    • 🔍数据结构
    • 📦数据库
    • 💻OS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
  • 关于

    • 📫关于我
  • 收藏

    • 网站
    • 资源
    • Vue资源
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

iqqcode

保持对技术的探索实践与热爱
首页
  • Android学习

    • 📁基础内容
    • 📺AndroidCore
    • 🎨Android-UI
    • 🏖️Components
    • 📊Fragment
    • 🔗网络操作
    • 🔏异步机制
    • 📦数据存储
    • 🗃️Gradle
  • 学习笔记

    • 『框架』笔记
    • 『Kotlin』笔记
    • 《Vue》笔记
    • 《Git》学习笔记
    • 『Bug踩坑记录』
  • ListView
  • RecyclerView
  • ViewPager
  • Java笔记

    • 🟠JavaSE
    • 🟢JavaWeb
    • 🔴JavaEE
    • ⚪JavaTopic
    • 🍳设计模式
  • 计算机基础

    • 📌计算机网络
    • 🔍数据结构
    • 📦数据库
    • 💻OS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
  • 关于

    • 📫关于我
  • 收藏

    • 网站
    • 资源
    • Vue资源
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • Android

  • Java

    • Kotlin线程基础
      • 1.创建线程
      • 2.线程锁
      • 3.wait(), notify() and notifyAll()
      • 4.线程相关第三方库
      • 5.当inline遇到synchronized
  • 『Bug踩坑记录』
  • Java
iqqcode
2021-06-17
目录

Kotlin线程基础

原文转载自: 请输入妮称.kotlin 线程基础[EB/OL].简书 https://www.jianshu.com/p/a684118c1b98,201807-24.


# 1.创建线程

在 kotlin中,有三种方式可以创建线程

1. 继承Thread类

object : Thread() {
  override fun run() {
    println("running from Thread: ${Thread.currentThread()}")
  }
}.start()
1
2
3
4
5

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

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

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

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

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

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
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 2.线程锁

在Java中,给方法加锁一般是使用synchronized关键字,但是在kotlin中,并没有这个关键字,取而代之的是@Synchronized注解。

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

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

fun methodWithSynchronizedBlock() {
  println("outside of a synchronized block: ${Thread.currentThread()}")
  synchronized(this) {
    println("inside a synchronized block: ${Thread.currentThread()}")
  }
}
1
2
3
4
5
6

# 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()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 4.线程相关第三方库

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

1.Kovenant library (opens new window) kotlin中的promise。

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

# 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)
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

反编译后的代码

    @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);
    }
1
2
3
4
5
6
7
8
9
10
11

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

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

编辑 (opens new window)
#bug
上次更新: 2022/07/02, 23:36:04
ARouter-Kotlin踩坑

← ARouter-Kotlin踩坑

最近更新
01
匿名内部类
10-08
02
函数式接口
10-08
03
ARouter-Kotlin踩坑
10-05
更多文章>
Theme by Vdoing | Copyright © 2021-2023 iqqcode | MIT License | 备案号-京ICP备2021028793号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×