[내배캠 Java 6기] Java 문법 5주차

ekkkyo_j·2024년 7월 31일

[내배캠 Java 6기] TIL

목록 보기
7/38
public class Main {
    public static void main(String[] args) {
        Runnable task = () -> {
            // 2번 thread는 thread1
            System.out.println("2번 => " + Thread.currentThread().getName());
            for (int i = 0; i < 100; i++) {
                System.out.print("$");
            }
        };

        // 1번 thread는 main
        System.out.println("1번 => " + Thread.currentThread().getName());
        Thread thread1 = new Thread(task);
        thread1.setName("thread1"); // thread의 이름 지정후

        thread1.start(); // start
    }
}

thread1은 위 Runnable task를 수행하는 thread이다.
thread1.setName("thread1")은 thread1의 이름을 설정하는 코드이다.
thread1.start()를 하면 task를 수행하는 thread1이 실행된다.
Thread.currentThread().getName()은 현재 실행되고 있는 thread의 이름을 출력하는 코드로, 1번 thread는 main을 2번 thread는 thread1을 출력한다.
main도 하나의 thread이다.

public class Main {
    public static void main(String[] args) {
        Runnable demon = () -> {
            for (int i = 0; i < 1000000; i++) {
                System.out.println(i+"번째 demon"); // 다 찍히지 못하고 종료 당함.
            }
        };


        // 우선순위가 낮다! => 상대적으로 다른 쓰레드에 비해 리소스를 적게 할당받는다.
        // 다른 쓰레드가 모두 종료되면 강제 종료 당한다.
        // vs foreground thread 사용자 쓰레드
        // : 우선순위가 높다. ex) Main 쓰레드
        // 사용자 쓰레드의 작업이 모두 끝나면 데몬 스레드도 자동으로 종료시킨다.
        Thread thread = new Thread(demon);
        thread.setDaemon(true);

        thread.start();

        for (int i = 0; i < 100; i++) {
            System.out.println(i+"번째 task");
        }
    }
}
public class Main {
    public static void main(String[] args) {
        Runnable task1 = () -> {
            for (int i = 0; i < 100; i++) {
                System.out.print("$");
            }
        };

        Runnable task2 = () -> {
            for (int i = 0; i < 100; i++) {
                System.out.print("*");
            }
        };

        Thread thread1 = new Thread(task1);
        thread1.setPriority(8);
        int threadPriority = thread1.getPriority();
        System.out.println("threadPriority = " + threadPriority);

        Thread thread2 = new Thread(task2);
        thread2.setPriority(2);

        thread1.start();
        thread2.start();
    }
}

thread의 우선순위를 정할 수 있는데, 이는 thread1.setPriority(숫자)로 정할 수있고, 주로 1~10까지 있다.

profile
게으르지만 성실히 공부하기^_^

0개의 댓글