A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new
Thread
object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.
thread는 프로그램의 실행 thread로서 jvm을 사용해 응용프로그램이 동시에 여러개의 스레드를 실행할 수 있게 한다.
스레드는 우선순위를 가지며 높은 순서부터 실행한다. 각 스레드는 데몬으로 표시되거나 표시되지 않을 수 있으며 스레드에서 실행한 코드가 새 스레드 개체를 생성하면 도일한 우선순위를 가지고 생성스레드가 데몬인 경우에만 데몬 스레드이다
Daemon Thread
쓰레드를 생성하는 방법은 두가지가 있는데 하나는 Thread 클래스를 상속받는 것이고 하나는 Runnable 인터페이스를 상속받는 것이다. 두가지 방법으로 만들면 아래 코드와 같다
public class ch01 {
public static void main(String[] args) {
PrimeThread p1 = new PrimeThread(143);
p1.start();
PrimeRun p2 = new PrimeRun(143);
new Thread(p2).start();
}
static class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
System.out.println("Extends Thread");
}
}
static class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
System.out.println("Implements Runnable");
}
}
}
Thread 클래스는 기본적으로 Runnable 인터페이스를 상속받는다. 즉 Thread 클래스를 상속받아 사용해도 상위에는 Runnable이 있으며 Thread 클래스는 run()
함수만 선언된 Runnable 인터페이스를 받아 재정의 해주고 추가적인 함수와 변수를 더 정의해준 것이다.
Thread 클래스를 상속받게 되면 함수 재정의가 필수는 아니다. 하지만 Runnable 인터페이스를 상속받으면 반드시 재정의 해줘야한다.
또한 Runnable 인터페이스를 상속받게 되면 다중 상속이 가능해진다. 만약 다른 클래스를 상속해야하는데 다중 스레도도 필요한 경우 해당 인터페이스를 구현하여 다중 상속을 할 수 있다.
static class PrimeRun implements Runnable, myInterface {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
System.out.println("primeRun");
System.out.println(getText());
}
@Override
public String getText() {
return "myInterface";
}
}
interface myInterface {
String getText();
}