이동식 저장소

[Kotlin] Thread 생성 및 실행 본문

Primary/Kotlin

[Kotlin] Thread 생성 및 실행

해스끼 2021. 1. 14. 10:26

코틀린에서 스레드를 만드는 방법은 다음의 4가지가 있다.

1. Thread 클래스 상속

class SimpleThread : Thread() {
    override fun run() {
        println("Hello! This is thread ${currentThread()}")
    }
}

val thread = SimpleThread()

2. Runnable 인터페이스 상속

class SimpleRunnable : Runnable {
    override fun run() {
        println("Hello! This is runnable ${hashCode()}")
    }
}

val runnable = SimpleRunnable()
val thread2 = Thread(runnable)

3. 익명 객체로 만들기

object : Thread() {
    override fun run() {
        println("Hello! This is object Thread ${currentThread()}")
    }
}

4. 람다식으로 만들기

Thread {
    println("Hello! This is lambda thread ${Thread.currentThread()}")
}

아니면 다음과 같이 헬퍼 함수를 직접 만들 수도 있다.

fun makeThread(
    start: Boolean = true,
    isDaemon: Boolean = false,
    contextClassLoader: ClassLoader? = null,
    name: String? = null,
    priority: Int = -1,
    block: () -> Unit
): Thread {
    val thread = object : Thread() {
        override fun run() {
            block()
        }
    }
    if (isDaemon)
        thread.isDaemon = true
    if (priority > 0)
        thread.priority = priority
    name?.let { thread.name = it }
    contextClassLoader?.let { thread.contextClassLoader = it }
    if (start) thread.start()
    return thread
}

위에서 만든 스레드를 모두 실행해 보자.

Hello! This is thread Thread[Thread-0,5,main]
Hello! This is lambda thread Thread[Thread-3,5,main]
Hello! This is object Thread Thread[Thread-2,5,main]
Hello! This is runnable 1213177452

스레드는 비동기적이므로 실행할 때마다 순서가 매번 달라질 수 있다.

'Primary > Kotlin' 카테고리의 다른 글

[Kotlin] Coroutines - Basics  (0) 2021.01.19
[Kotlin] Sequence  (0) 2021.01.15
[Kotlin] Collections 확장 함수  (0) 2021.01.13
[Kotlin] 데이터 클래스  (0) 2021.01.08
[Kotlin] 위임  (0) 2021.01.06
Comments