Thread

말하는 감자·2025년 1월 3일
0

자바 중급

목록 보기
19/21
post-thumbnail

개념

쓰레드란

  • 동시에 여러 작업을 수행
  • 현재 실행되고 있는 프로그램을 프로세스라 하는데, 이때 하나의 프로세스 안에서도 여러개의 흐름이 동작할 수 있다(멀티스레딩). 이것을 Thread라 한다.
  • 자바에서 스레드를 만드는 방법은 크게 Thread 클래스를 상속받는 방법과 Runnable 인터페이스를 구현하는 방법이 있다.

extend Thread

Thread를 상속 받아서 쓰레드를 생성하는 방법
-> java.lang.Thread 클래스를 상속받는다. 그리고 Thread가 가지고 있는 run()메서드를 오버라이딩한다.

Implements Runnable

Runnable 인터페이스를 구현해서 쓰레드를 만드는 방법
-> Runnable 인터페이스가 가지고 있는 run()메서드를 구현한다

Code 예시(Thread 상속)

public class MyThread1 extends Thread {
        String str;
        public MyThread1(String str){
            this.str = str;
        }

        public void run(){
            for(int i = 0; i < 10; i ++){
                System.out.print(str);
                try {
                    //컴퓨터가 너무 빠르기 때문에 수행결과를 잘 확인 할 수 없어서 Thread.sleep() 메서드를 이용해서 조금씩 쉬었다가 출력할 수 있게한다. 
                    Thread.sleep((int)(Math.random() * 1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } 
        } 
    }
    public class ThreadExam1 {
        public static void main(String[] args) {
            // MyThread인스턴스를 2개 만듭니다. 
            MyThread1 t1 = new MyThread1("*");
            MyThread1 t2 = new MyThread1("-");

            t1.start();
            t2.start();
            System.out.print("!!!!!");  
        }   
    }
  • Thread를 상속받았으므로 MyThread1은 Thread이다
  • 쓰레드를 생성하고 Thread 클래스가 가지고 있는 start() 메소드를 호출한다.

Code 예시(Runnable 인터페이스 구현)

public class MyThread implements Runnable {
    String str;
    public MyThread(String str){
        this.str=str;
    }

    public void run(){
        for(int i=0;i<10;i++){
            System.out.println(str);
            try {
                Thread.sleep((int)(Math.random()*100));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class ThreadExam {
    public static void main(String[] args) {
        MyThread t1=new MyThread("*");
        MyThread t2=new MyThread("-");

        Thread thread1=new Thread(t1);
        Thread thread2=new Thread(t2);

        thread1.start();
        thread2.start();
        System.out.println("end");
    }
}
  • MyThread는 Thread를 상속받지 않았기 때문에 Thread가 아니다 따라서 Thread를 생성하고 해당 생성자에 MyThread를 넣어서 Thread를 생성한다.
  • Thread 클래스가 가진 start()메소드를 호출한다.
profile
주니어개발자(?)

0개의 댓글