본문 바로가기

TIL

[TIL] 프로세스와 스레드, 모던 자바(filter) [Java]

프로세스

  • 우리가 프로그램을 실행하기 위해 OS한테 요청하면 OS는 프로그램이 사용할 수 있는 Code, Data, Stack, Heap 영역을 할당
  • Code
    - 우리가 작성한 code
    Data
    - 전역변수, 정적변수, 배열 등 초기화된 데이터 저장공간
  • Stack
    - 지역변수, 매개변수 리턴 변수
  • Heap
    - new(), malloc() 등 동적으로 할당된 변수

 

멀티스레드 사용방법

1. Thread 클래스 상속 받아 사용

public class TestThread extends Thread {
	@Override
    public void run() {
    	// 스레드 수행작업 작성
    }
}

TestThread thread = new TestThread(); // 스레드 생성
thread.start(); // 스레드 실행

 

2. Runnable 인터페이스 사용

public class TestRunnable implements Runnable {
	@Override
    public void run() {
    	// 스레드 수행작업
    }
}

Runnable run = new TestRunnable();
Thread thread = new Thread(run); // 스레드 생성
thread.start(); // 스레드 실행

 

3. 람다식 사용

Runnable task = () -> {
	// 스레드 수행 작업
};

Thread thread = new Thread(task); // 스레드 생성
thread.setName("thread");
thread.start(); // 스레드 실행

 

1번 방식보다는 2번과 3번 방식을 더 자주 사용

 

데몬 스레드

  • 보이지 않는 곳에서 실행되는 낮은 우선순위를 가진 스레드
  • ex) 가비지 컬랙터
  • 우선순위가 낮아서 다른 스레드에 비해 리소스를 적게 할당 받는다.
  • JVM은 사용자 스레드 작업이 끝나면 데모 스레드도 자동 종료시킨다. 즉, 데몬 스레드의 작업이 다 끝나지 않아도 종료시킨다.
Runnable demon = () -> {
	for (int i = 0; i < 1000000; ++i) {
    	System.out.println((i + 1) + "번째 demon");
    }
};

Thread thread = new Thread(demon);
thread.setDaemon(true); // 데몬스레드로 설정
thread.start();

for (int i = 0; i < 100; ++i) {
	System.out.println((i + 1) + "번째 main");
}
  • 100번째 main이 출력되면 demon이 1000000번째가 출력되지 않더라도 프로그램이 종료된다.
  • setDaemon(true)
    - 이걸로 데몬 스레드로 설정하는 것이다.

멀티스레드에서의 우선순위

  • 우선순위가 높게 할당 된 스레드에게 더 많은 리소스를 할당해준다.
  • 하지만 우선순위가 높은 것이 먼저 처리될 확률이 높은 것이지, 무조건 먼저 처리한다는 것은 아니다.
Thread thread = new Thread(task);
thread.setPriority(8); // 우선순위 설정

int threadPriority = thread.getPriority(); // 우선순위 값 가져오기
  • 우선순위: 1 ~ 10
    - default 우선순위 값은 5
  • 이 우선순위의 범위는 OS가 아닌 JVM에서 설정한 우선순위이다.

모던 자바

filter()

  • 특정 조건을 만족하는 것을 반환
// 가격이 16200원 이하인 책 제목 조회
List<Book> priceBook = bookList.stream()
	.filter(b -> b.getPrice() <= 16200)
    .collect(Collectors.toList());