Java 멀티스레딩(Multithreading)

이진호·2022년 9월 14일
0

Java Multithreading

목록 보기
1/3
post-thumbnail

멀티스레딩은 CPU 활용을 극대화하기 위해 프로그램의 두 개 이상의 부분을 동시에 실행하는 Java 기능입니다. 각각의 부분은 스레드(thread)라고 불리는 프로세스 내의 경량 프로세스가 됩니다.

스레드는 두 가지 방법으로 생성할 수 있습니다.

Thread 클래스 상속

java.lang.Thread 클래스를 상속받아 클래스를 생성할 수 있습니다. Thread 클래스를 상속 받으면 run() 메서드를 재정의 할 수 있는데, run() 메서드의 내용이 스레드로 동작하게 됩니다. Thread 클래스를 상속받은 객체를 생성후, start() 메서드를 호출하여 스레드를 실행시킬 수 있습니다. start() 메서드는 Thread 객체 내부의 run() 메서드를 호출합니다.

// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
    public void run()
    {
        try {
            // Displaying the thread that is running
            System.out.println(
                "Thread " + Thread.currentThread().getId()
                + " is running");
        }
        catch (Exception e) {
            // Throwing an exception
            System.out.println("Exception is caught");
        }
    }
}
 
// Main Class
public class Multithread {
    public static void main(String[] args)
    {
        int n = 8; // Number of threads
        for (int i = 0; i < n; i++) {
            MultithreadingDemo object
                = new MultithreadingDemo();
            object.start();
        }
    }
}

Runnable 인터페이스 구현

java.lang.Runnable 인터페이스를 구현하는 클래스를 생성한 후 run() 메서드를 재정의 합니다. 이후 Thread 개체를 인스턴스화하고 이 개체에서 start() 메서드를 호출합니다.


// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
    public void run()
    {
        try {
            // Displaying the thread that is running
            System.out.println(
                "Thread " + Thread.currentThread().getId()
                + " is running");
        }
        catch (Exception e) {
            // Throwing an exception
            System.out.println("Exception is caught");
        }
    }
}
 
// Main Class
class Multithread {
    public static void main(String[] args)
    {
        int n = 8; // Number of threads
        for (int i = 0; i < n; i++) {
            Thread object
                = new Thread(new MultithreadingDemo());
            object.start();
        }
    }
}

Thread 클래스 vs Runnable 인터페이스

  1. 만약 Thread 클래스를 상속받는 경우, 해당 클래스는 더이상 다른 클래스를 상속할 수 없습니다(자바는 다중 상속을 지원하지 않음). 하지만 Runnable 인터페이스를 구현하는 경우, 해당 클래스는 여전히 다른 클래스를 상속할 수 있습니다.
  2. Thread 클래스를 상속받는 경우, Runnable 인터페이스에는 없는 yield(), interrupt() 등의 기능을 사용할 수 있습니다.
  3. Runnable 인터페이스를 사용하는 경우, 여러 스레드에서 공유할 수 있는 객체를 얻을 수 있습니다.

출처

0개의 댓글