본문 바로가기

IT/Java

18_자바 System 클래스 : exit 메소드, 프로그램 실행 소요 시간 구하기

00. System 클래스

-- java.lang.System 클래스를 이용하면 운영체제의 일부 기능을 이용할 수 있다.

-- System 클래스의 모든 필드와 메소드는 static으로 구성되어 있다.

 

01. exit 메소드

-- 개발을 하다보면 JVM을 강제로 종료시킬 때가 있는데, 이 때 exit 메소드를 사용한다.

-- int형 매개값을 지정하도록 되어있는데, 이 값을 종료상태값이라고 부른다.

-- 일반적으로 정상 종료일 경우 0으로 지정하고 비정상종료일 경우 다른 값을 지정한다.

-- System.exit()이 실행되면 보안관리자(Security Manager)의 checkExit() 메소드가 자동 호출되는데, 이 때 종료상태값을 조사하여 특정 값이 입력되었을 때만 JVM이 종료되도록 할 수 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ExitExample {
    public static void main(String[] args) {
        //exit의 매개값에 특정 값이 입력된 경우에만 종료시키도록 보안 관리자를 설정
        System.setSecurityManager(new SecurityManager(){
            @Override
            public void checkExit(int status) {
                if(status != 5) {
                    throw new SecurityException();
                }
            }
        });
        
        for(int i=0; i<10; i++) {
            System.out.println(i);
            try {
                System.exit(i);
            } catch (SecurityException e) {    //exception이 발생해도 for문은 계속 유지 됨
        }
        }
    }
 
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

02. 프로그램 실행 소요 시간 구하기

- 현재 시각을 구할 때 System.currentTimeMillis() 또는 System.nanoTime()를 사용한다.

- 이것을 활용하여 프로그램의 실행 소요 시간을 구할 수 있다.

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
public class SystemTimeExample {
    public static void main(String[] args) {
        long time1 = System.nanoTime();
        
        int sum = 0;
        for(int i=1; i<=100000; i++) {
            sum += i;
        }
        
        long time2 = System.nanoTime();
        
        System.out.println("1~100000까지의 합 : " + sum);
        System.out.println("소요시간 : " + (time2 - time1) + "나노초");
        
        time1 = System.currentTimeMillis();
        sum = 0;
        for(int i=1; i<=20000000; i++) {
            sum += i;
        }
        time2 = System.currentTimeMillis();
        System.out.println("1~20000000까지의 합 : " + sum);
        System.out.println("소요시간 : " + (time2 - time1) + " 밀리세컨드");
    
    }
    
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter