[Java] 쓰레드(Thread) 생성 방법과 공유객체 이용해보기

Hee·2024년 4월 24일

Java 복습

목록 보기
45/46
post-thumbnail

쓰레드(Thread)

: 동시에 여러 작업을 수행하기 위한 실행 흐름을 나타낸다. 각 쓰레드는 독립적인 실행 경로를 가지며, 하나의 프로세스 내에서 여러 쓰레드가 동작할 수 있다. 이를 통해 여러 작업을 병렬 또는 동시에 처리할 수 있다.



Thread 생성방법 두가지

1. Thread를 상속 받아서 쓰레드를 생성하는 방법

java.lang.Thead 클래스를 상속받는다. 그리고 Thread 클래스가 가지고 있는 run() 메소드를 오버라이딩 한다.

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

@override
public void run(){
	for(int i=0; i<10; i++){
    	System.out.print(str);
    }
    try{
    	// 0~1초 사이씩 쉬면서 출력
    	Tread.sleep((int)(Math.random() * 1000));
    }catch(InterruptException e){
    	e.printStackTrace();
    }
}

Thread 클래스를 상속받은 MyTread1을 사용하는 클래스
Thread클래스를 상속받았으므로 MyTread1은 Thread이다.
Thread를 생성하고, Thead 클래스가 가지고 있는 start() 메소드를 호출한다.

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("!!!!!");
    }
}

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

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

@override
public void run(){
	for(int i=0; i<10; i++){
    	System.out.print(str);
    }
    try{
    	// 0~1초 사이씩 쉬면서 출력
    	Tread.sleep((int)(Math.random() * 1000));
    }catch(InterruptException e){
    	e.printStackTrace();
    }
}

Runnable 인터페이스를 구현하는 MyTread1을 사용하는 클래스
MyTread2는 Thread를 상속받지 않았기 때문에 Thread가 아니다.
Thread를 생성하고, 해당 생성자에 MyThread2를 넣어서 Thread를 생성한다.
Thread 클래스가 가진 start() 메소드를 호출한다.

public class ThreadExam1{
	public static void main(String[] args){
    	// MyThread 인스턴스를 2개 만듦.
        MyThread1 r1 = new MyThread1("*");
        MyThread1 r2 = new MyThread1("-");
        
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        
        t1.start();
        t2.start();
        System.out.print("!!!!!");
    }
}

클래스는 하나의 부모클래스만 상속받을 수 있기 때문에, Thread 클래스를 상속받지 못하는 경우 Runnable 인터페이스를 사용하여 Thread를 생성할 수 있다.



공유객체를 이용한 Thread 사용방법

공유객체란, 하나의 객체를 여러 개의 Thread가 사용한다는 것을 의미한다.

MusicPlayer 3명은 하나의 MusicBox를 사용할 것이다.
MusicBox라는 클래스가 있다고 가정한다.
해당 클래스는 3개의 메소드를 가지고 있다.
각각의 메소드는 1초 이하의 시간동안 10번 반복하면서, 어떤 음악 문구를 출력한다.
이러한 MusicBox를 사용하는 MusicPlayer를 3명 만들어 볼 것이다.

공유객체 MusicBox 클래스

public class MusicBox{
	public void playMusicA(){
    	for(int i=0; i<10; i++){
        	System.out.println("신나는 음악!!!!");
            try{
            	Thread.sleep((int)(Math.random()*1000));
            }catch(InerruptedException e){
            	e.printStackTrace();
            }
        }
    }
    
    public void playMusicB(){
    	for(int i=0; i<10; i++){
        	System.out.println("조용한 음악!!!!");
            try{
            	Thread.sleep((int)(Math.random()*1000));
            }catch(InerruptedException e){
            	e.printStackTrace();
            }
        }
    }
    
    public void playMusicC(){
    	for(int i=0; i<10; i++){
        	System.out.println("슬픈 음악!!!!");
            try{
            	Thread.sleep((int)(Math.random()*1000));
            }catch(InerruptedException e){
            	e.printStackTrace();
            }
        }
    }
    
}

MusicBox를 가지는 Thread객체 MusicPlayer 클래스

public class MusicPlayer extends Thread{
	int type;
    MusicBox musicBox;
    
    public MusicPlayer(int type, MusicBox musicBox){
    	this.type = type;
        this.musicBox = musicBox;
    }
    
    // type이 무엇이냐에 따라서 musicBox가 가지고 있는 메소드가 다르게 호출
    @override
    public void run(){
    	switch(type){
        	case 1 : musicBox.playMusicA(); break;
            case 2 : musicBox.playMusicB(); break;
            case 3 : musicBox.playMusicC(); break;
        }
    }
}

MusicBox와 MusicPlayer를 이용하는 MusicBoxExam1 클래스

public class MusicBoxExam1{
	public static void main(String[] args){
    	MusicBox box = new MusicBox();
        
         MusicPlayer kim = new MusicPlayer(1, box);
         MusicPlayer lee = new MusicPlayer(2, box);
         MusicPlayer kang = new MusicPlayer(3, box);
         
         // MusicPlayer쓰레드를 실행 
         kim.start();
         lee.start();
         kang.start(); 
    }
}

0개의 댓글