λ‚˜λ§Œμ˜ μ˜€λž˜λ‹¬λ¦¬κΈ°λ₯Ό ν•˜λŠ” μ‚¬λžŒ

Become a ghost

Programming/JAVA

[JAVA] μžλ°” μŠ€λ ˆλ“œ (Thread) λž€?

jennnnna 2024. 7. 4. 00:39

λ™μž‘ν•˜κ³  μžˆλŠ” ν”„λ‘œκ·Έλž¨μ„ ν”„λ‘œμ„ΈμŠ€ (Process) 라고 ν•œλ‹€. 
ν•œ 개의 ν”„λ‘œμ„ΈμŠ€μ—μ„œλŠ” ν•œ κ°€μ§€μ˜ 일을 ν•˜μ§€λ§Œ 
μŠ€λ ˆλ“œ(Thread) λ₯Ό μ΄μš©ν•˜λ©΄ ν•˜λ‚˜μ˜ ν”„λ‘œμ„ΈμŠ€ μ•ˆμ— 두 개 μ΄μƒμ˜ 일을 λ™μ‹œμ— 진행할 수 μžˆλ‹€. 

public class Sample extends Thread {
    public void run() {  // Thread λ₯Ό μƒμ†ν•˜λ©΄ run λ©”μ„œλ“œλ₯Ό κ΅¬ν˜„ν•΄μ•Ό ν•œλ‹€.
        System.out.println("thread run.");
    }
    
    
        public static void main(String[] args) {
        Sample sample = new Sample();
        sample.start();  // start()둜 μ“°λ ˆλ“œλ₯Ό μ‹€ν–‰ν•œλ‹€.
    }
}

μ–΄λ–€ ν΄λž˜μŠ€μ—μ„œ μŠ€λ ˆλ“œλ₯Ό 상속 λ°›μœΌλ©΄ run () λ©”μ„œλ“œλ₯Ό κ΅¬ν˜„ν•΄μ•Ό ν•œλ‹€. 
main λ©”μ†Œλ“œμ—μ„œ start ν•΄μ€€λ‹€. 
메인 λ©”μ†Œλ“œμ—μ„œ start λ₯Ό ν•΄μ£ΌλŠ” μˆœκ°„, μŠ€λ ˆλ“œμ— μžˆλŠ” run 이 μž‘λ™λ˜λŠ” 원리이닀. 

메인 λ©”μ†Œλ“œκ°€ μ’…λ£Œλ˜μ–΄λ„ μŠ€λ ˆλ“œλŠ” λ™μž‘ν•œλ‹€. 
λ™μ‹œμ— μ‹œμž‘ν•΄λ„ μˆœμ„œλŠ” 보μž₯λ˜μ§€ μ•Šκ³ , λ˜‘κ°™μ΄ λ™μž‘ν•˜λŠ” μŠ€λ ˆλ“œλ₯Ό λ™μ‹œμ— 10개λ₯Ό μ‹€ν–‰μ‹œμΌ°μ„ λ•Œ 
μ–΄λ–€ μŠ€λ ˆλ“œκ°€ λ¨Όμ € λλ‚ μ§€λŠ” λͺ¨λ¦„. 

μŠ€λ ˆλ“œλ₯Ό μ°¨λ‘€λŒ€λ‘œ μ‹€ν–‰μ‹œν‚€κ³  μ‹ΆμœΌλ©΄ ?
join 을 κ±Έλ©΄ λœλ‹€. 

import java.util.ArrayList;

public class Sample extends Thread {
    int seq;
    public Sample(int seq) {
        this.seq = seq;
    }

    public void run() {
        System.out.println(this.seq+" thread start.");
        try {
            Thread.sleep(1000);
        }catch(Exception e) {
        }
        System.out.println(this.seq+" thread end.");
    }

    public static void main(String[] args) {
        ArrayList<Thread> threads = new ArrayList<>();
        for(int i=0; i<10; i++) {
            Thread t = new Sample(i);
            t.start();
            threads.add(t);
        }

        for(int i=0; i<threads.size(); i++) {
            Thread t = threads.get(i);
            try {
                t.join(); // t μ“°λ ˆλ“œκ°€ μ’…λ£Œν•  λ•ŒκΉŒμ§€ κΈ°λ‹€λ¦°λ‹€.
            }catch(Exception e) {
            }
        }
        System.out.println("main end.");
    }
}

μŠ€λ ˆλ“œ 객체 t ν•˜λ‚˜μ”© μ‹€ν–‰λœλ‹€. 
각 μŠ€λ ˆλ“œ μ•ˆμ— μžˆλŠ” run () 싀행이 μ™„λ£Œ 되면 κ·Έ λ‹€μŒ μŠ€λ ˆλ“œκ°€ μ‹€ν–‰ 됨. 

 

tcp ν†΅μ‹ μœΌλ‘œ μžλ°” μ½˜μ†”μ°½μ— μ±„νŒ…λ°© κ΅¬ν˜„ν•˜κ³  μžˆλŠ”λ° 
μŠ€λ ˆλ“œ κ°œλ…μ„ ν—·κ°ˆλ €ν•˜λŠ” 것 κ°™μ•„μ„œ κ°€μž₯ 기초적인 μŠ€λ ˆλ“œ κ°œλ…λΆ€ν„° λ‹€μ‹œ λ΄€λ‹€. 
근데 μ±„νŒ…λ°© κ΅¬ν˜„ν•  λ•Œ join μ“Έ 일은 μ—†μ—ˆλ˜ κ±° 같은데..