둘 이상의 실행 흐름을 갖는 프로그램을 멀티스레드 프로그램(Multi-Thread Program)이라고 합니다.
Multi-Thread-Program을 만들때 해야하는 세가지
1) Thread를 상속받아 클래스를 작성합니다.
2) public void run() 메소드 선언합니다.
3) 메인에서 해당 Thread를 객체생성 후 start()메소드를 통해 시작시켜줍니다.
A부터 Z까지 출력하는 메인 스레드(MultiThreadEx1)
class MultiThreadEx1 { public static void main(String[] args) { System.out.println(); DigitThread thread = new DigitThread(); //Thread thread1 = new DigitThread(); Thread를 상속하기 때문에 이렇게 선언해도 된다. thread.start(); for(char ch='A';ch<='Z';ch++){ System.out.print(ch); } } }
0부터 9까지 출력하는 스레드(DigitThreadEx1)
class DigitThread extends Thread{ public void run(){ for(int i=0;i<10;i++){ System.out.print(i); } } }
ABC0123456789DEFGHIJKLMNOPQRSTUVWXYZ
자바 가상 기계는 멀티스레드 프로그램을 실행할 때 프로그램의 실행시간을 아주 작은 간격으로 나누어서 스레드들을 번갈아 실행합니다.
sleep()메소드를 이용하면, 주어진 시간동안 기다리게 됩니다.
이 메소드를 이용해서 숫자와 문자를 좀더 고르게 섞여서 출력되게 할 수 있습니다.
class MultiThreadEx1 { public static void main(String[] args) { System.out.println(); DigitThread thread = new DigitThread(); //Thread thread1 = new DigitThread(); Thread를 상속하기 때문에 이렇게 선언해도 된다. thread.start(); for(char ch='A';ch<='Z';ch++){ System.out.print(ch); try{ Thread.sleep(500); }catch(InterruptedException e){ System.out.println(e.getMessage()); } } } }
class DigitThread extends Thread{ public void run(){ for(int i=0;i<10;i++){ System.out.print(i); try{ Thread.sleep(500); }catch(InterruptedException e){ System.out.println(e.getMessage()); } } } }
A0B12CD3E4F56GH78IJ9KLMNOPQRSTUVWXYZ
'2013 > Java' 카테고리의 다른 글
[Java] 멀티스레드 프로그램(2) - 스레드간의 데이터 교환 (0) | 2013.11.12 |
---|---|
[Java] 로또(Lotto) 프로그램(1) (0) | 2013.11.11 |
[Java] 멀티스레드 프로그램(1) (0) | 2013.11.08 |
[Java] 버블정렬(1) (0) | 2013.11.08 |
[Java] Radom클래스(1) (0) | 2013.11.08 |
[Java] StringTokenizer 클래스(1) (0) | 2013.11.07 |