본문으로 바로가기

[자바]쓰레드(Thread)

category Java 2017. 8. 10. 17:32

안녕하세요~~ 이번시간엔 자바 thread (스레드) 에 대해 알아보겠습니다.


쓰레드는 기본적으로 백그라운드에서 작업이 되는데요.


이런 쓰레드를 적용하는 방법에는 여러가지가 있습니다.


먼저 첫번째로 Thread 를 상속(extend) 받아 사용하는 방법입니다.

public class ThreadEx extends Thread {
	private int[] temp;
	
	public ThreadEx(String threadname) {
		// TODO Auto-generated constructor stub
		super(threadname);
		
		temp = new int[10];
		for(int i = 0 ; i < temp.length ; i ++) {
			temp[i] = i;
		}
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i : temp) {
			try {
				Thread.sleep(1000);
				
			} catch (Exception e) {
				// TODO: handle exception
			}
			System.out.println("스레드돈다 : " +currentThread().getName());
			System.out.println("temp : " + temp[i]);
		}
	}
	
	public static void main(String[] args) {
		ThreadEx st = new ThreadEx("스레드");
		st.start();
	}
}


Thread 를 상속받아 1초마다 temp 를 출력하는 예제를 보았는데요 이와 같은코드를 똑같이 Runnable 인터페이스를 사용하여 구현 할 수 있습니다.

public class RunnableEx implements Runnable{
	private int[] temp;
	
	public RunnableEx() {
		// TODO Auto-generated constructor stub
		temp = new int[10];
		for(int i = 0 ; i < temp.length ; i ++) {
			temp[i] = i;
		}
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i : temp) {
			try {
				Thread.sleep(1000);
				
			} catch (Exception e) {
				// TODO: handle exception
			}
			System.out.println("temp : " + temp[i]);
			System.out.println("name : " + Thread.currentThread().getName());
		}
		
	}

	public static void main(String[] args) {
		RunnableEx ct = new RunnableEx();
		Thread t = new Thread(ct,"스레드??????");
		t.start();
	}
}



이번포스팅으로 Thread 를 상속받는 방법과 Runnable 인터페이스를 사용하는 방법으로 쓰레드를 사용해 봤습니다.


다음번엔 thread 의 join 을 알아보겠습니다.

'Java' 카테고리의 다른 글

[자바]채팅프로그램 만들기  (3) 2017.08.17
[자바]쓰레드(thread) - join  (1) 2017.08.10
[자바](AWT)+member/anonymous innerClass  (1) 2017.08.10
[자바](AWT)간단한 구조  (0) 2017.08.10
[자바]String값 기본  (0) 2017.08.09