/ JAVA

객체지향 프로그래밍 복습 (10) Thread

[JAVA] 객체지향 프로그래밍 복습 (10) Thread

자바(Java)는 C언어에 객체 지향적 기능을 추가하여 만든 C++과는 달리, 처음부터 객체 지향 언어로 개발된 프로그래밍 언어입니다. 자바는 자바 가상 머신(JVM, Java Virtual Machine)을 사용하여, 운영체제와는 독립적으로 동작할 수 있습니다. 따라서 자바는 어느 운영체제에서나 같은 형태로 실행될 수 있습니다. 바로 이러한 점이 수많은 개발자로 하여금 자바를 사용하게 하는 원동력이 되고 있습니다. 현재 자바는 전 세계에서 가장 많이 사용하는 프로그래밍 언어 중 하나입니다.

쓰레드 Thread

동작하고 있는 프로그램을 프로세스(Process)라고 합니다. 보통 한 개의 프로세스는 한 가지의 일을 하지만, 이 쓰레드를 이용하면 한 프로세스 내에서 두 가지 또는 그 이상의 일을 동시에 할 수 있게 됩니다.

쓰레드 객체를 만들 때는 쓰레드 클래스를 상속받거나 Runnable 인터페이스를 구현하는 방법이 있습니다.

Thread 클래스

Thread 클래스를 이용하여 2개의 쓰레드에서 현재 시간을 출력하도록 구현합니다.

DateDisplayerThread.java

import java.util.Date;
import java.text.SimpleDateFormat;

//Thread 클래스 상속
public class DateDisplayerThread extends Thread{

	public void run() {
		//현재시간 포맷 설정
		SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");

		for (int i = 0; i < 7; i++){
			try {
				Date currentTime = new Date();
				String time = format.format(currentTime);
				//Thread 실행 시 이름과 시간 출력
				System.out.println(this.getName()+" : "+time);
				//2초 대기
				sleep(2000);
			} catch (InterruptedException e) { }
		}	
	}


	public static void main(String[] args) {
		System.out.println("Testing Program 1 using Thread Class");
		//start() 명령으로 run() 실행
		new DateDisplayerThread().start();
		new DateDisplayerThread().start();
	}
}

결과

DateDisplayerRunnable. java

import java.util.Date;
import java.text.SimpleDateFormat;

//Runnable 인터페이스 구현
public class DateDisplayerRunnable implements Runnable {
	public void run() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
		for(int i=0;i<7;i++){
			try {
				Date currentTime = new Date();
				String time = format.format(currentTime);
				System.out.println(Thread.currentThread().getName()+" : "+time);
				Thread.sleep(2000);
			} catch (InterruptedException e) { }
		}
	}

	public static void main(String[] args) {
		System.out.println("Testing Program 2 using Runnable Interface");
		
		//클래스 인스턴스 생성
		DateDisplayerRunnable r = new DateDisplayerRunnable();
		
		//Thread 생성
		Thread thread1 = new Thread(new Runnable() {
			@Override
			public void run() {
				//현재시간 포맷 설정
				SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
				for(int i=0;i<7;i++){
					try {
						Date currentTime = new Date();
						String time = format.format(currentTime);
						//Thread 이이름과 시간 출력
						System.out.println(Thread.currentThread().getName()+" : "+time);
						Thread.sleep(2000);
					} catch (InterruptedException e) { }
				}
			}
		}, "Thread 1");
		thread1.start();

		Thread thread2 = new Thread(new Runnable() {
			@Override
			public void run() {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
				for(int i=0;i<7;i++){
					try {
					Date currentTime = new Date();
					String time = format.format(currentTime);
					System.out.println(Thread.currentThread().getName()+" : "+time);
					Thread.sleep(2000);
				} catch (InterruptedException e) { }
				}
			}
		}, "Thread 2");
		thread2.start();
	}
}

결과