Kotlin Threadの作成と実行
Kotlinでスレッドを実装する方法は、次の4つがある。
Threadクラスの継承による実装
クラスを継承して実装した例は次のとおりである。
class ThreadExtends : Thread(){
override fun run() {
println("Hello! This is extends ${currentThread()}")
}
}
fun main() {
val thread = ThreadExtends()
thread.start()
}
Output:
Hello! This is extends Thread[Thread-0,5,main]
Runnableインターフェースの継承による実装
Runnableインターフェースを実装した例は次のとおりである。
class ThreadRunnable : Runnable {
override fun run() {
println("Hello! This is runnable ${hashCode()}")
}
}
fun main() {
val thread = Thread(ThreadRunnable())
thread.start()
}
Output:
Hello! This is runnable 109369515
匿名オブジェクトによる実装
匿名オブジェクトで実装した例は次のとおりである。
fun main() {
val thread = object : Thread() {
override fun run() {
println("Hello! This is object Thread ${currentThread()}")
}
}
thread.start()
}
Output:
Hello! This is object Thread Thread[Thread-0,5,main]
ラムダ式による実装
ラムダ式で実装した例は次のとおりである。
fun main() {
var thread = Thread {
println("Hello! This is lambda thread ${Thread.currentThread()}")
}
thread.start()
}
Output:
Hello! This is lambda thread Thread[Thread-0,5,main]
次のように、ラムダ式でオブジェクトを作成し、振る舞いを追加した関数として実装することもできる。
fun startThread(): Thread {
val thread = Thread {
println("Hello! This is start lambda thread ${Thread.currentThread()}")
}
thread.start()
return thread;
}
fun main() {
startThread()
}
Output:
Hello! This is start lambda thread Thread[Thread-0,5,main]