1. Thread() // 새로운 스레드 객체 할당
2. Thread(String name) // 스레드 이름이 name인 새로운 스레드 객체 할당
3. Thread(Runnable target) // Runnable target이 구현된 스레드 객체 할당
4. Thread(Runnable target, String name) // Runnable target이 구현되고, 스레드 이름이 name인 새로운 스레드 객체 할당
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
MyThread myThreadWithName = new MyThread("myThreadname");
myThread.run();
myThreadWithName.run();
}
}
class MyThread extends Thread {
MyThread(){}
MyThread(String name){
super(name);
}
public void run() {
System.out.println(this.getName());
}
}

public class Main {
public static void main(String[] args) {
Runnable runnable = new MyThread_Runnable();
Thread thread = new Thread(runnable);
Thread threadWithName = new Thread(runnable, "myThreadName");
thread.start();
threadWithName.start();
}
}
class MyThread_Runnable implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}


함수형 인터페이스로, 1개의 메소드만을 가지므로 람다로 사용할 수 있다.
스레드를 구현하기 위한 템플릿.
sleep(
MyThread.java
public class MyThread implements Runnable {
@Override
public void run() {
int cnt = 0;
while (!Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName());
Main.threadSleep(Thread.currentThread(), 500);
cnt++;
if (cnt == 20) {
Thread.currentThread().interrupt();
System.out.println(Thread.currentThread().toString() + "-인터럽트됨]");
}
}
}
}
run() 메서드를 실행하면 cnt 값을 증가시키다가 cnt == 20일 때, 인터럽트한다.
Main.java
public class Main {
public static void main(String[] args) {
Runnable runnable = new MyThread();
Thread thread1 = new Thread(runnable, "thread1");
Thread thread2 = new Thread(runnable, "thread2");
thread1.start();
thread2.start();
}
static void threadSleep(Thread thread, long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
System.out.println(thread.toString() + "-인터럽트됨]");
thread.interrupt();
}
}
}
main 메서드는 스레드 2개를 생성 후 start()를 호출한다.
threadSleep 메서드는 주어진 time동안 스레드를 일시중지한다.