Thread Status
thread 는 start() 명령을 받으면 Runnable 상태로 들어가게 됨 이후 cpu 배분을 받으면 Run 상태로 들어감
Not Runnable 상태에 들어가는 경우와 복귀(?) 시간
- sleep(time) - time 만큼 시간이 지난 후
- wait() - notify() 받을 때까지
- join() - 다른 스레드의 결과가 나올 때까지
Thread 우선순위 Thread.MIN_PRIORITY(=1) ~ Thread.MAX_PRIORITY(=10) 디폴트 우선 순위 : Thread.NORMAL_PRIORITY(=5) G.C 의 PRIORITY = 8 정도 ?( 찾아봐야함) 우선 순위가 높은 Thread 가 CPU 배분을 받을 확률이 높음 setPriority() / getPriority()
join()
- 스레드의 리턴값이 필요할 때? ?
Join() 사용 방법
ThreadJoin threadJoin = new ThreadJoin(1,50);
ThreadJoin threadJoin2 = new ThreadJoin(51,100);
threadJoin.start();
threadJoin2.start();
try {
threadJoin.join();
threadJoin2.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
int total = threadJoin.total + threadJoin2.total;
Thread 종료
- 무한 반복의 경우
- while(flag) 의 flag 값을 false 로 바꾸어서 종료
Multi Thread 에서 동기화
- critical section
- 두 개 이상의 thread 가 동시에 접근 하는 경우 문제가 생길 수 있기 때문에 동시에 접근 할 수 없는 영역
- semaphore 를 얻은 thread만 접근 할 수 있음
- semaphore
- 특별한 형태의 시스템 객체
- get/release 두 개의 기능이 있음
- 하나의 thread 만이 semapore를 얻을 수 있음
- 나머지 thread 는 대기 상태 ( blocking )
동기화
- synchronization
- 두 개의 thread가 같은 객체에 접근 할 경우, 동시에 접근 함으로써 오류가 발생
- 동기화는 임계영역에 접근한 경우 공유자원을 lock 하여 다른 thread의 접근을 제어
- 동기화를 잘못 구현하면 deadlock에 빠질 수 있다
자바에서는 synchronized 메서드나 synchronized 블럭을 사용 synchronized 블럭
- 현재 객체 또는 다른 객체를 lock으로 만든다
synchronized(참조형 수식){
수행문;
}
synchronized 메서드
- 객체의 메소드에 synchronized 키워드 사용
- 현재 이 메서드가 속해있는 객체에 lock을 건다
- 자바에서는 deadlock을 방지하는 기술이 제공되지 않으므로 되도록이면 synchronized 메서드에서 다른 synchronized 메서드는 호출하지 않도록 한다.
thread 를 깨우는 방법?
- Object method 의 wait() , notifiy() 를 사용
- Not Runnable thread 중에 서 아무거나 깨움
- notifyAll() 의 경우 wait() 중인 thread를 전부 깨움
- 자바에서는 notifyAll() 권장
public synchronized String lendBook() {
Thread t = Thread.currentThread();
while (books.isEmpty()) {
try {
System.out.println(t.getName() + " : waiting start");
wait();
System.out.println(t.getName() + " : waiting end");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
String book = books.remove(0);
System.out.println(t.getName() + " : " + book + "를 빌려감");
return book;
}
public synchronized void returnBook(String book) {
Thread t = Thread.currentThread();
books.add(book);
notifyAll();
System.out.println(t.getName() + " : " + book + "를 반환함");
}
notifyAll() 사용시 while 사용
- 미할당 객체?는 다시 wait()
thread run() , start() 차이
run()
url: https://kim-jong-hyun.tistory.com/101
title: "[JAVA] - Thread.start()와 Thread.run()의 차이"
description: "JAVA로 Thread 관련 프로그래밍을 학습하다보면 start() 메서드와 run() 메서드를 보게되는데 두 메서드를 실행하게되면 Thread의 run() 메서드를 실행하게 된다. 다만 이 두 메서드의 동작방식을 제대로 이해하지 못하고 사용하면 프로그램이 원치않게 실행 될 수 있다. 이 두 메서드의 동작방식의 차이를 한번 살펴보자. Thread.start() main 메서드에 현재 실행된 Thread 이름을 출력하고 Thread 인스턴스를 5개 생성한다. 인스턴스 생성시 생성자로 Runnable 타입을 주입해준 후 start() 메서드를 실행하였다. 출력결과로 main Thread와 Thread 인스턴스 5개가 출력된 걸 확인할 수 있다. Thread.run() 이번에는 run() 메서드를 실행해보았다.."
host: kim-jong-hyun.tistory.com
favicon: https://t1.daumcdn.net/tistory_admin/favicon/tistory_favicon_32x32.ico
image: https://img1.daumcdn.net/thumb/R800x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FbcaKJm%2Fbtrj7Svbb8A%2FHchvtU3Ea1PKxhiw8Rxc2K%2Fimg.jpg
Socket