HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
🧵
멀티쓰레드, 동시성 프로그래밍
/
🧵
Java Concurrency and Multithreding
/
Create, starting and stopping threads in Java

Create, starting and stopping threads in Java

Create threads in Java

Thread 클래스 상속
Thread 생성 with Runnable을 인자로 가지는 생성자
 

실행중인 Thread 객체의 참조를 얻는법

Join a thread - wait for the Java Thread to terminate

 
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(); }
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 currentThread = Thread.currentThread()
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회 출력!