Skip to content

자바 Concurrent 프로그래밍 소개

Jeonghyun Kang edited this page Jun 5, 2022 · 2 revisions

자바 멀티쓰레드 프로그래밍

Thread 상속

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Hello " + Thread.currentThread().getName());
    }
}
MyThread myThread  = new MyThread();
myThread.start();    // Hello Thread-0

Runnable 구현 또는 람다

Thread thread = new Thread(() -> {
    System.out.println("Thread " + Thread.currentThread().getName());
});
thread.start();    // // Hello Thread-1

쓰레드 주요 기능

sleep

public static void main(String[] args) {
    Thread thread = new Thread(() -> {
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread " + Thread.currentThread().getName());
    });
    thread.start();

    System.out.println("Hello: " + Thread.currentThread().getName());
}

result

Hello: main
Thread Thread-0

Interrupt

Thread thread = new Thread(() -> {
    while(true) {
        System.out.println("Thread " + Thread.currentThread().getName());
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            System.out.println("exit!");
            return;
        }
    }
});
thread.start();

System.out.println("Hello: " + Thread.currentThread().getName());
Thread.sleep(3000L);
thread.interrupt();

result

Hello: main
Thread Thread-0
Thread Thread-0
Thread Thread-0
exit!

join

Thread thread = new Thread(() -> {
    System.out.println("Thread " + Thread.currentThread().getName());
    try {
        Thread.sleep(3000L);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
});
thread.start();

System.out.println("Hello: " + Thread.currentThread().getName());
try {
    thread.join();    // Thread를 기다린다.
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println(thread + " is finished");

result

Hello: main
Thread Thread-0
Thread[Thread-0,5,] is finished

Clone this wiki locally