[JAVA] 62. 스레드와 멀티 스레딩

서회정's avatar
Feb 21, 2025
[JAVA] 62. 스레드와 멀티 스레딩

1. 스레드 기본

notion image
package ex19; public class Th01 { public static void main(String[] args) { // CPU -> 메인 쓰레드 //새로운 생명 주기를 만드는 것=쓰레드를 만드는 것 // 모든 쓰레드가 종료되어야 자바도 종료됨. // 쓰레드의 생명주기 영역 = 타겟 Thread t1 = new Thread(() -> { // 분신1 for (int i = 0; i < 10; i++) { System.out.println("분신1 : " + i); try { Thread.sleep(500); // 0.5초 } catch (InterruptedException e) { throw new RuntimeException(e); } } }); t1.start(); // => 윈도우(리눅스)야 남는 쓰래드 하나 만들어서 run좀 때려줘 Thread t2 = new Thread(() -> { // 분신2 for (int i = 0; i < 10; i++) { System.out.println("분신2 : " + i); try { Thread.sleep(500); // 0.5초 } catch (InterruptedException e) { throw new RuntimeException(e); } } }); System.out.println("메인 쓰레드 종료"); } }
notion image
 
 

2. Thread 그림그리기 예제

코드

package ex19; class MyFile { public void write() { try { Thread.sleep(5000); System.out.println("파일 쓰기 완료"); } catch (InterruptedException e) { throw new RuntimeException(e); } } } class 화가 { public void 그림그리기() { System.out.println("그림 그리기 완료"); } } // 화가 public class Th03 { public static void main(String[] args) { MyFile myFile = new MyFile(); 화가 painter = new 화가(); painter.그림그리기(); new Thread(() -> { myFile.write(); }).start(); painter.그림그리기(); } }

결과

notion image
 
 

 

3. 숫자 카운터 프로그램

코드

package ex19; import javax.swing.*; //JFrame 자바로 그림그리는 도구 public class Th05 extends JFrame { private boolean state = true; private int count = 0; private int count2 = 0; private JLabel countLabel; private JLabel count2Label; public Th05() { setTitle("숫자 카운터 프로그램"); setVisible(true); setSize(300, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 레이아웃 매니저 설정 setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); // 숫자를 표시할 레이블 생성 countLabel = new JLabel("숫자1: " + count); count2Label = new JLabel("숫자2: " + count2); countLabel.setAlignmentX(CENTER_ALIGNMENT); count2Label.setAlignmentX(CENTER_ALIGNMENT); add(countLabel); add(count2Label); // 멈춤 버튼 생성 JButton increaseButton = new JButton("멈춤"); increaseButton.setAlignmentX(CENTER_ALIGNMENT); add(increaseButton); // 버튼에 액션 리스너 추가 increaseButton.addActionListener(e -> { state = false; }); new Thread(() -> { while (state) { try { Thread.sleep(1000); count++; countLabel.setText("숫자1 : " + count); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } }).start(); new Thread(() -> { while (state) { try { Thread.sleep(1000); count2++; count2Label.setText("숫자2 : " + count2); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } }).start(); } public static void main(String[] args) { new Th05(); } }

결과

notion image
 

💡멀티 스레딩 사용 이유 / 유형

 
📌
스레드 사용 이유 (인스타나 유튜브 썸네일이 회색으로 뜨는 화면을 예를 들어 사용할 수 있음) 1. 동시에 하고싶을 때 2. IO가 일어날 때 스레드에서 받은 데이터를 리턴 받아서 응용하고 싶을때!! 1. 타이밍 맞추기 (임시방편 - 그래도 쓰는 사람 많음) ex) 키보드 창 올라왔을 때 스크롤탑 값도 같이 변하는 앱 2. 리스너 (부하가 너무 큼) 3. 콜백 (제일 좋음)
 
 

4. 스레드가 리턴해야할 때

 
package ex19; //콜백 class Store implements Runnable { int qty; @Override public void run() { // 통신 -> 다운로드 try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } qty = 5; } } public class Th06 { public static void main(String[] args) { int totalQty = 10; Store store = new Store(); Thread t1 = new Thread(store); t1.start(); try { Thread.sleep(200); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("재고수량 :" + (store.qty + totalQty)); } }
 

5. 리스너

 
package ex19; //콜백 class Store implements Runnable { Integer qty; @Override public void run() { // 통신 -> 다운로드 try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } qty = 5; } } public class Th06 { public static void main(String[] args) { int totalQty = 10; Store store = new Store(); Thread t1 = new Thread(store); t1.start(); while (true) { if (store.qty != null) break; try { Thread.sleep(10); System.out.println("돌았습니다."); // 몇바퀴 돌았는지 확인용 출력 } catch (InterruptedException e) { throw new RuntimeException(e); } } System.out.println("재고수량 :" + (store.qty + totalQty)); } }
 

6. 콜백

 
package ex19; //콜백 // 1) 콜백 메서드 만들기 interface CallBack { void 입고(int qty); // 리턴 받고 싶은 인수(파라미터)를 만들어주면 된다. } class Store implements Runnable { // 2) 리턴이 필요한 곳으로 가서 콜백 메소드 전달 받기 Integer qty; CallBack callBack; public Store(CallBack callBack) { this.callBack = callBack; } @Override public void run() { // 통신 -> 다운로드 try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } qty = 5; callBack.입고(qty); // 3) 종료 시 콜백 메서드 호출 } } public class Th06 { public static void main(String[] args) { int totalQty = 10; Store store = new Store(qty -> { System.out.println("재고수량 :" + (qty + totalQty)); }); Thread t1 = new Thread(store); t1.start(); } }
Share article

clubnerdy