프로세스와 스레드
작업 스레드의 생성과 실행
Runnable은 실행할 수 있는 코드를 가지고 있는 객체이다.
Runnable에는 run() 메소드 하나만 정의 되어있으며, 구현 클래스에서는 이를 재정의해서 사용한다.
Runnable t = new Thread(new Runnable(){
public void run(){
// Task 내용
}
})
Runnable t = new Thread(()->{
// Task 내용
})
t.start();
public class WorkerThread extends Thread{
@Override
public void run(){
}
}
Thread t = new WorkerThread();
t.start();
스레드의 이름
스레드는 자신의 이름을 갖고 있다. 메인 스레드는 main, 우리가 생성한 스레드는 Thread-n 이라는 이름로 생성된다.
thread.setName("Name"); // 이름 세팅
thread.getName(); // 이름 가져오기
Thread currentThread = Thread.currentThread(); // 현재 스레드에 대한 참조
동시성과 병렬성

자바의 스레드 스케줄링
동기화 메소드와 블록
- 멀티스레드 프로그램에서 스레드가 객체를 공유해서 작업하는 경우
public synchronized void methodName(){
// 임계영역
}public void methodName(){
// 코드 1
public synchronized void setMem(int 공유객체) {
// 코드 2(임계영역)
}
// 코드 3
}