컴퓨터에는 멀티태스킹을 위한 두 가지 도구가 있다. 바로 프로세스 와 스레드.
프로그램을 실행하는 순간 메모리에 올라가고 동작하게되는데 이 상태의 프로그램을 프로세스라고 한다.
프로그램이 실행되면 메모리에 적재되고, 프로세스가 된다. 프로세스는 독립적으로 메모리에 등록되므로 여러개의 프로그램을 동시에 실행할 수 있다.
자바에서 스레드 생성 방법
- thread 클래스를 상속하여 run메서드 구현
- Runnable 인터페이스 구현
스레드는 클래스에 Thread를 상속 받은 다음, Thread가 가지고 있는 run()메서드를 사용해 생성. 만약 상속이 어려운 경우에는 Runnable 인터페이스를 상속해 구현 할 수 있다.
ex)
public class MyThread extends Thread {
//스레드가 시작하면 자동으로 실행!
@Override
public void run() {
int sum = 0;
for(int i = 1; i <= 100; i++){
sum = sum+i;
}
System.out.println("합 : " + sum);
String threadName = Thread.currentThread().getName();
System.out.println("현재 스레드 : " + threadName);
}
}
public class ThreadMain{
public static void main(String[] args){
MyThread th = new MyThread();
th.setName("더하기 스레드");
//스레드 시작!
th.start();
System.out.println(th.isAlive());
}
}
-> true
합 : 5050
현재 스레드 : 더하기 스레드
ex2) 청기백기 게임!
public class FlagGame {
public static void main(String[] args) {
Runable white = () -> {
white(true){
System.out.println("백기올려");
}
};
Runable blue = () -> {
while(true) {
System.out.println("청기올려");
}
};
Thread w = new Thread(white);
Thread b = new Thread(blue);
w.start();
b.start();
}
}