티스토리 뷰
스레드를 생성하고 활용하는 방법은 2가지가 있다.
- Thread 객체 상속받기
- Runnable 인터페이스 상속받기
## Thread 객체를 상속받기
: 스레드로 사용할 클래스를 정의 한 후 Thread 클래스를 상속받는다.
Thread 클래스 객체를 생성하여 실행하기 위해서는 run() 메소드를 오버라이딩 해주어야 한다.
class NewT extends Thread{
@override
public void run(){
실행!
}
}
public class Example {
public static void main(String[] args)
NewT t = new NewT();
t.start();
}
}
스레드 객체인 t를 실행하기 위해서는 start() 메소드로 실행시켜주면 된다.
start() 메소드를 실행하면 run() 메소드가 실행된다.
오라클의 start메소드 정의
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
==> 스레드가 실행을 시작한다, JVM 은 스레드의 run() 메소드를 호출한다.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
==> 두 스레드가 동시에 실행이 되며, start메소드를 호출할 메소드(main)와 run 메소드를 실행할 스레드 인 두 스레드!
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution
==> 스레드를 한 번 이상 실행하는 것은 옳지 않다고 하며, 한 번 실행된 후 재실행은 되지 않는다.
'개인공부 > JAVA' 카테고리의 다른 글
Exception - throws (학교공부) (0) | 2021.09.17 |
---|---|
Thread - Sync (0) | 2021.09.10 |
Exception (0) | 2021.09.09 |
배열, 기본클래스 (0) | 2021.05.05 |
JAVA - Inner Class, Lambda , Stream (0) | 2021.03.21 |