JAVA/JAVA8 관련
Concurrent 프로그래밍 소개
JUMP개발자
2022. 5. 20. 16:48
Concurrent 소프트웨어
동시에 여러 작업을 할 수 있는 소프트웨어
- 예) 웹 브라우저로 유튜브를 보면서 키보드로 문서에 타이핑을 할 수 있음.
- 예) 녹화를 하면서 인텔리J로 코딩을 하고 워드에 적어둔 문서를 보거나 수정할 수 있음.
자바에서 지원하는 컨커런트 프로그래밍
- 멀티프로세싱 (ProcessBuilder)
- 멀티쓰레드
자바 멀티쓰레드 프로그래밍
- Thread / Runnable
- 실행 순서가 보장되지 않음.
public class Thread1 {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
System.out.println("main Thread : " + Thread.currentThread().getName());
// java8 style
/*Thread java8Style = new Thread(() -> {
System.out.println("람다식 new Thread : " + Thread.currentThread().getName());
});
java8Style.start();
*/
}
// java 8 이전 스타일
static class MyThread extends Thread{
@Override
public void run() {
System.out.println("new Thread : " + Thread.currentThread().getName());
}
}
}
순서상 new Thread가 main Thread보다 먼저 출력돼어야 할 것 같지만 쓰레드의 자원 할당은 OS에 의해 결정되므로 순서가 보장되지 않음.
Thread를 상속받는 방식
static class MyThread extends Thread{
@Override
public void run() {
System.out.println("new Thread : " + Thread.currentThread().getName());
}
}
Runnable을 구현하는 방식
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("new Thread : " + Thread.currentThread().getName());
}
});
Sleep, 현재 Thread 대기시키는 기능
public class Thread2 {
public static void main(String[] args) {
Thread thread = new Thread(()-> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("new Thread(람다식) :" + Thread.currentThread().getName());
});
thread.start();
System.out.println("main Thread : " + Thread.currentThread().getName());
}
// 매우 높은 확률로 main Thread 로그가 먼저 찍힘
}
Interrupt, 다른 쓰레드 깨우기
쓰레드가 Sleep하는 동안 쓰레드를 깨우면 Interrupted Exception이 발생한다.
Interrupt 메서드를 통하여 깨우는 것이 가능하다.
public class Thread3 {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while(true) {
System.out.println("반복중... : " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("interrupt!!!!");
return;
}
}
});
thread.start();
System.out.println("main Thread : " + Thread.currentThread().getName());
Thread.sleep(3000);
thread.interrupt();
}
}
Join, 이전 쓰레드가 끝날때까지 기다리기
다른 쓰레드가 끝날 때까지 기다리려면 Join을 사용하면된다.
public class Thread4 {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
});
thread.start();
System.out.println("waiting for " + thread.getName());
thread.join();
System.out.println("finished : " + thread.getName());
}
}