elevne's Study Note

Thread, Future, ScheduledFuture, Runnable 본문

Backend/Java

Thread, Future, ScheduledFuture, Runnable

elevne 2023. 4. 13. 22:15

Thread

 

Thread 클래스는 Java 에서 제공하는 클래스 중 하나로 멀티쓰레드 프로그래밍을 구현하는데 사용된다.

 

 

Thread()
Thread(Runnable target)
Thread(String name)
Thread(Runnable target, String name)
Thread(ThreadGroup group, Runnable target)
Thread(ThreadGroup group, String name)
Thread(ThreadGroup group, Runnable target, String name)

 

 

Thread 클래스는 start(), run(), sleep(), yield(), join(), interrupt() 등 다양한 메서드를 제공한다. start() 메서드는 쓰레드를 실행, run() 메서드는 쓰레드가 실행될 때 호출되는 메서드, sleep() 메서드는 일정시간 동안 쓰레드를 대기 상태로 만드는 메서드이다. yield() 메서드는 다른 쓰레드에게 실행을 양보, join() 메서드는 쓰레드가 끝날 때까지 기다리고 interrupt() 메서드는 쓰레드를 중지시킨다. 

 

 

public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("MyThread is running...");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new MyThread();
        thread.start();
    }
}

 

 

또 위에서 ThreadGroup 이라는 클래스도 사용되었는데, 이는 쓰레드들을 그룹으로 묶어서 관리하는데 사용되는 클래스이다. 

 

 

ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)

 

 

name 매개변수는 새로운 ThreadGroup 객체의 이름을 지정, parent 매개변수는 ThreadGroup 객체를 지정하는 매개변수이다. ThreadGroup 클래스는 interrupt(), setDaemon(), setMaxPriorty(), setUncaughtExceptionHandler() 메서드를 제공한다.

 

 

 

Future

 

Future 인터페이스는 Java 에서 제공하는 인터페이스 중 하나로 비동기적인 작업을 수행할 때 사용된다. 비동기작업은 작업을 시작한 쓰레드와 결과를 처리하는 쓰레드가 다를 수 있기 때문에 작업이 완료될 때까지 기다리는 동안 다른 작업을 수행할 수 있다.

 

 

boolean cancel(boolean mayInterruptIfRunning) 작업을 취소. mayInterruptIfRunning 파라미터는 실행 중인 쓰레드가 인터럽트될지 여부를 결정한다.
boolean isCancelled() 작업 취소 여부 반환
boolean isDone() 작업 완료 여부 반환
V get() throws InterruptedException, ExecutionException 작업이 완료될 때까지 블로킹되고 결과를 반환
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 지정된 시간 동안 작업이 완료될 때까지 블로킹되고, 결과를 반환

 

 

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> {
    Thread.sleep(1000);
    return 1 + 2;
});

while (!future.isDone()) {
    System.out.println("Waiting for the future to be done...");
    Thread.sleep(500);
}

int result = future.get();
System.out.println("Result: " + result);

executor.shutdown();

 

 

ExecutorService 를 생성하고 submit() 메서드를 사용하여 작업을 제출한다. submit() 메서드는 작업을 실행하고 Future 객체를 반환한다. 

 

 

 

ScheduledFuture

 

ScheduledFuture 클래스는 자바에서 제공하는 인터페이스로, 예약된 작업의 상태와 결과를 나타낸다. 해당 인터페이스의 schedule 메서드를 사용하여 예약된 작업을 만들 때 반환되는 객체이다. ScheduledFuture 인터페이스는 Future 인터페이스를 확장하여 구현된다. 따라서 Future 인터페이스에서 제공되는 메서드 뿐만 아니라 추가적인 메서드를 제공한다. 

 

 

boolean cancel(boolean mayInterruptIfRunning) 스케줄된 작업을 취소. mayInterruptIfRunning 파라미터는 실행 중인 쓰레드가 인터럽트 될지에 대한 여부를 결정
boolean isCancelled() 스케줄된 작업이 취소되었는지에 대한 여부
boolean isDone() 스케줄된 작업이 완료되었는지에 대한 여부
V get() throws InterruptedException, ExecutionException 스케줄된 작업이 완료될 때까지 블로킹되고, 결과를 반환
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 지정된 시간 동안 스케줄된 작업이 완료될 때까지 블로킹되고, 결과를 반환

 

 

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> future = executor.schedule(() -> {
    System.out.println("Hello from the future!");
}, 1, TimeUnit.SECONDS);

while (!future.isDone()) {
    System.out.println("Waiting for the future to be done...");
    Thread.sleep(500);
}

executor.shutdown();

 

 

위 예시는 ScheduledExecutorService 를 생성하고 schedule 메서드를 사용하여 작업을 스케줄한다. schedule 메서드는 작업을 지정된 시간 이후에 실행한다. 또 이 메서드는 ScheduledFuture 객체를 반환한다. 그리고 isDone() 메서드를 사용하여 ScheduledFuture 객체가 완료될 때까지 기다린 다음 shutdown() 메서드를 호출하여 ScheduledExecutorService 를 종료한다.

 

 

 

Runnable

 

Runnable 인터페이스는 Java 에서 제공하는 인터페이스 중 하나로 쓰레드가 실행할 수 있는 작업을 정의하는데 사용된다. Runnable interface 는 아래와 같이 단 하나의 메서드만을 가지고 있다.

 

 

public interface Runnable {
    public abstract void run();
}

 

 

Runnable 인터페이스는 단순히 run() 메서드를 정의하는 것이기에 이 인터페이스를 구현하고 run 메서드를 구현한 객체를 만들어 쓰레드에 전달하면 해당 객체의 run() 메서드가 실행된다.

 

 

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("MyRunnable is running...");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }
}

'Backend > Java' 카테고리의 다른 글

Java Enum  (0) 2023.04.19
Java Functional Interface  (0) 2023.04.18
Java Keywords ...  (0) 2023.04.12
Cache 에 대하여  (0) 2023.03.27
Java HttpServer 사용해보기  (0) 2023.02.23