다음과 같이 Thread class를 상속받아, run() 메서드를 Override 시켜준다.
public class MyThread extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ": run()");
}
}
사용할 곳에서 생성을 하고, start() 메서드를 통해, Thread를 시작한다.
public class MyThreadMain {
public static void main(String[] args) throws InterruptedException {
MyThread thread = new MyThread();
thread.start();
}
}
무조건 Start() 메서드로 Thread를 실행하고, run() 메서드로는 실행 하지 않도록 한다
- run() 메서드를 실행하면, Override 된
System.out.println
코드를 main Thread에서 실행하고 끝
위의 코드를 실행하면 다음과 같은 스택 영역이 생성된다.
해당 코드의 핵심 포인트는, main thread
가 run()
메서드를 실행 한 것이 아니라, Thread-0
스레드가 run()
메서드를 실행 한 것이다.
main thread
는 단지, start()
메서드를 통해서 Thread-0
스레드에게 실행 지시를 내린 것 뿐이다.
해당 main Thread
와 Thread-0
는 이제부터 병렬적으로 일을 처리한다. 즉 머리가 두개로 나눠진 것이다.
Thread 상속과 다르게 Runnable 인터페이스는 Implements 해서 구현한다.
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ": run()");
}
}
Runnable을 구현한 class를 Thread에 생성자 주입하여 사용한다
public class MyRunnableMain {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
Runnable
은@FunctionalInterface
작성되어있어,익명함수
or 람다 식으로 활용 가능하다.
public class MyRunnableMain {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
log("run() start");
}
});
thread.start();
}
}
public class MyRunnableMain {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
log("run() start");
log("test");
});
thread.start();
}
}