Create threads in Java
Thread 클래스 상속
static class MyThread extends Thread{ @Override public void run() { System.out.println("MyThread running"); System.out.println("MyThread finished"); } } public static void main(String[] args) { Thread thread = new MyThread(); thread.start(); }
Thread 생성 with Runnable을 인자로 가지는 생성자
static class MyTask implements Runnable{ @Override public void run() { System.out.println("MyTask Running"); System.out.println("MyTask Finishing"); } } public static void main(String[] args) { Thread thread = new Thread(new MyTask()); thread.start(); }
public static void main(String[] args) { Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("MyTask Running"); System.out.println("MyTask Finishing"); } }); thread.start(); }
public static void main(String[] args) { Thread thread = new Thread(() -> { System.out.println("MyTask Running"); System.out.println("MyTask Finishing"); }); thread.start(); }
실행중인 Thread 객체의 참조를 얻는법
Thread currentThread = Thread.currentThread()
Join a thread - wait for the Java Thread to terminate
public class ThreadExample10 { public static void main(String[] args) { Runnable runnable = () ->{ for (int i = 0; i < 5; i++) { sleep(1000); System.out.println("Running"); } }; Thread thread = new Thread( runnable ); thread.setDaemon(true); thread.start(); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } } //메인 쓰레드가 실행 동시에 종료 되기 때문에 아무것도 출력되지 않고 프로그램이 종료된다.
public class ThreadExample10 { public static void main(String[] args) { Runnable runnable = () ->{ for (int i = 0; i < 5; i++) { sleep(1000); System.out.println("Running"); } }; Thread thread = new Thread( runnable ); thread.setDaemon(true); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } } //Main Thread는 자식 쓰레드가 종료 될 때까지 Blocked 된다. //Running 5회 출력!