본문 바로가기

자바

32. 쓰레드

쓰레드란 하나의 프로세스에서 여러 가지 일을 하는 것이다. 예를 들어 노래를 들으며 문서작업을 하거나 채팅을 하며 게임을 하는 경우가 있다. java는 멀티스레드를 지원한다. 한가지는 객체 하나당 n개의 스레드를 공유하는 방식이고 다른 하나는 객체 하나당 하나의 스레드가 존재하는 방식이다. 

 

쓰레드를 구현하는데는 두가지 방법이 있다. 한가지는 Runnable 인터페이스를 이용한 구현이고 다른 한가지는 Thread 클래스를 상속하여 구현하는 방법이다.

 

다음은 Runnable 인터페이스를 이용하여 쓰레드를 구현한 것이다.

package com.thread;

public class HowToUseRunnable implements Runnable {

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName()); //쓰레드의 이름을 출력
		System.out.println("ThreadTest");
		
		for(int i = 0; i < 10; i++) {
			System.out.println(i);
			try {
				Thread.sleep(1000); //1초 쉬어감
			}
			catch (Exception e){}
		}
	}
}

 

다음은 Thread클래스를 상속받아 쓰레드를 구현한 것이다.

package com.thread;

public class HowToUseThread extends Thread {
	public void run() {
		System.out.println(Thread.currentThread().getName()); //쓰레드의 이름을 출력
		for(int i = 0; i < 10; i++) {
			System.out.println("abc");
			try {
				Thread.sleep(500);
			} 
			catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
}

 

다음은 여러개의 쓰레드들을 실행시킨 것이다.

package com.thread;

public class MainClass {
	public static void main(String[] args) {
		
		HowToUseRunnable hr = new HowToUseRunnable();
		HowToUseThread ht = new HowToUseThread();
		
		Thread thread = new Thread(hr, "A"); //hr의 쓰레드 이름을 A라고 지정
		ht.setName("B"); //ht의 쓰레드 이름을 B라고 지정
		
		//thread1과 ht와 main문은 따로 따로 각자 할 일을 한다. 순차적인 개념이 절대로 아니다.
		thread.start();
		ht.start();
		System.out.println(thread.currentThread().getName()); //main이 찍히는 이유, 현재 main문에서 thread가 돌아가기 때문에
	}
}

 

 

다음은 객체 1개의 여러 개의 쓰레드를 구현하는 것이다.

package com.thread;

public class HowToControlManyThread implements Runnable {
	int testNum = 0;
	
	public void run() {
		for(int i = 0; i < 10; i++) {
			if(Thread.currentThread().getName().equals("A")){
				System.out.println("-----------------------------");
				testNum++;
			}
			System.out.println("Thread Name : " + Thread.currentThread().getName() + "testNum : " + testNum);
			try {
				Thread.sleep(500);
			} 
			catch (Exception e) {}
		}

	}
}

 

package com.thread;

public class MainClass {
	public static void main(String[] args) {
		HowToControlManyThread hc = new HowToControlManyThread();
		
		Thread thread0 = new Thread(hc, "A");
		Thread thread1 = new Thread(hc, "B");
		thread0.start();
		thread1.start();
		
		System.out.println(Thread.currentThread().getName());
		System.out.println("MainClass");
	}
}

'자바' 카테고리의 다른 글

33. 싱크로나이즈  (0) 2019.08.21
31. Java 입출력(I/O)  (0) 2019.08.19
30. Java Collection2  (0) 2019.08.14
29. Java collection1  (0) 2019.08.12
28. 예외 처리  (0) 2019.08.11