quilt code

[고급자바] Thread (2) 본문

daily/고급자바

[고급자바] Thread (2)

김뱅쇼 2023. 2. 7. 20:24

1. 스레드의 수행시간 체크

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class T03ThreadTest {
    public static void main(String[] args) {
        
        Thread th = new Thread(new MyRunner());
        
        // UTC(Universal Time Coordinated 협정 세계 표준시)를 사용하여 1970년 1월 1일 0시 0분 0초를 기준으로 경과한 시간을 밀리세컨드(1/1000초)단위로 나타낸다.
        long startTime = System.currentTimeMillis();
        
        th.start();    // th 스레드 작업 시작
        try {
            th.join();  // 현재 실행중인 스레드에서 작업중인 스레드(th스레드)가 종료될 때까지 기다린다.
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        
        System.out.println("경과 시간(ms) : " + (endTime - startTime));
    }
 
}
cs

 

2. 1 ~ 10억까지의 합계를 구하는 메소드

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyRunner implements Runnable {
 
    @Override
    public void run() {
        long sum = 0;
        for(int i=1; i<1000000000; i++) {
            sum += i;
        }
        System.out.println("합계 : " + sum);
        
    }
    
}
cs

 

3. 1 ~ 20억 까지의 합계를 구하는데 걸린 시간 체크하기 

   ** 전체 합계를 구하는 작업을 단독으로 했을 때 (1개의 스레드를 사용했을 때)와 여러 스레드로 분할해서 작업했을 때의 시간을 확인해보자.

 

 

1 ) 단독으로 처리 했을 때

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void main(String[] args) {
        // 단독으로 처리 했을 때...
        Thread sm = new SumThread(1L, 2000000000L);
        
        long startTime = System.currentTimeMillis();
        
        sm.start();
        
        try {
            sm.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        long endTime = System.currentTimeMillis();
        
        System.out.println("단독으로 처리할 때의 처리 시간 : " + (endTime - startTime));
        System.out.println("\n\n");
cs

 

2) 여러 스레드로 나누어 처리 했을 때

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 여러 스레드로 나누어 처리 했을 때...
        Thread[] sumThs = new SumThread[] {
                new SumThread(         1L,   50000000L),
                new SumThread(  50000000L, 1000000000L),
                new SumThread(1000000001L, 1500000000L),
                new SumThread(1500000001L, 2000000000L),
        };
        
        startTime = System.currentTimeMillis();
        
        for(Thread th : sumThs) {
            th.start();
        }
        
        for(Thread th : sumThs) {
            try {
                th.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        endTime = System.currentTimeMillis();
        
        System.out.println("여러 스레드로 나누어 처리했을 때의 처리 시간 : "
                            + (endTime - startTime));
    }    
}
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class SumThread extends Thread {
    private long min, max;
    
    public SumThread(long min, long max) {
        this.min = min;
        this.max = max;run();
    }
    @Override
    public void run() {
        long sum = 0;
        for(long i=min; i<=max; i++) {
            sum += i;
        }
        System.out.println(min + " ~ " + max + "까지의 합 : " + sum);
 
    }
}
cs

 

4. 단일 스레드에서의 사용자 입력 처리

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package kr.or.ddit.basic;
 
import javax.swing.JOptionPane;
 
/**
 *   단일 스레드에서의 사용자 입력 처리
 */
 
public class T05ThreadTest {
    public static void main(String[] args) {
        
        String str = JOptionPane.showInputDialog("아무거나 입력하세요");
        System.out.println("입력한 값은 " + str + "입니다.");
        
        for(int i=10; i>=1; i--) {
            System.out.println(i);
            
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                
            }
            
        }
    }
 
}
cs

 

 

5. 멀티 스레드를 이용한 사용자 입력 처리

 ** 입력 여부를 확인하기 위한 변수 선언

 ** 모든 스레드에서 공용으로 사용할 변수

 

1
2
3
4
5
6
7
8
9
10
    public static boolean inputCheck = false;
    
    public static void main(String[] args) {
        Thread th1 = new DataInput();
        th1.start();
        
        Thread th2 = new CountDown();
        th2.start();
    }
 
cs

 

 

6. 사용자 입력을 처리하는 스레드

 

1
2
3
4
5
6
7
8
9
10
11
class DataInput extends Thread {
    
    @Override
    public void run() {
        String str = JOptionPane.showInputDialog("아무거나 입력하세요");
        
        T06ThreadTest.inputCheck = true;
        
        System.out.println("입력한 값은 " + str + "입니다.");
    }
}
cs

 

 

 

7. 카운트다운 처리를 위한 스레드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class CountDown extends Thread {
    
    @Override
    public void run() {
        for(int i=10; i>=1; i--) {
            
            if(T06ThreadTest.inputCheck) {
                return;
            }
            System.out.println(i);
            
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                
            }
        }
        
        // 10초가 경과되었는데도 입력이 없으면 프로그램을 종료한다.
        System.out.println("10초가 지났습니다. 프로그램을 종료합니다.");
        System.exit(0);  // 프로그램을 종료시키는 명령 (스레드가 있든 없든 강제 종료)    
    }
}
cs

 

 

8. 우선 순위

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class T08ThreadPriorityTest {
    public static void main(String[] args) {
        
        System.out.println("최대 우선순위 : " + Thread.MAX_PRIORITY);
        System.out.println("최소 우선순위 : " + Thread.MIN_PRIORITY);
        System.out.println("보통 우선순위 : " + Thread.NORM_PRIORITY);
        
        Thread[] ths = new Thread[] {
            new ThreadTest1(),
            new ThreadTest1(),
            new ThreadTest1(),
            new ThreadTest1(),
            new ThreadTest1(),
            new ThreadTest2()
        };
        
        // 우선 순위는 start() 메소드를 호출하기 전에 설정해 주어야 한다.
        for(int i=0; i<ths.length; i++) {
            if(i == 5) {
                ths[i].setPriority(Thread.MAX_PRIORITY);
            } else {
                ths[i].setPriority(Thread.MIN_PRIORITY);
            }
        }
        
        // 설정된 우선순위 출력하기
        for(Thread th : ths) {
            System.out.println(th.getName() + "의 우선순위 : " + th.getPriority());
        }
        
        // 스레드 시작
        for(Thread th : ths) {
            th.start();
        }
    } 
 
}
 
class ThreadTest1 extends Thread {
    
    @Override
    public void run() {
        for(char ch='A'; ch<='Z'; ch++) {
            System.out.println(ch);
            
            // 아무것도 하지 않는 반복문 (시간 때우기용)
            for(long i=1; i<=1000000000L; i++) {
                
            }
        }
    }
}
 
// 알파벳 소문자를 출력하는 스레드
class ThreadTest2 extends Thread {
    
    @Override
    public void run() {
        for(char ch='a'; ch<='z'; ch++) {
            System.out.println(ch);
            
            // 아무것도 하지 않는 반복문 (시간 때우기용)
            for(long i=1; i<=1000000000L; i++) {
                
            }
        }
    }
}
cs

 

'daily > 고급자바' 카테고리의 다른 글

[고급자바] 컴퓨터와 가위바위보 프로그램  (0) 2023.02.07
[고급자바] Thread(3)  (0) 2023.02.07
[고급자바] Thread (1)  (0) 2023.02.06
[고급자바] Annotation  (0) 2023.02.06
[고급자바] 호텔 과제  (0) 2023.02.03