Java Thread

λ™μ‹œμ„±

  • Concurrency

    • Logical

    • Single Core / Multi Core

  • Parallel

    • Physical

    • Multi Core

JavaλŠ” JVM (Java Virtual Machine) μœ„μ—μ„œ λ™μž‘ν•˜λ―€λ‘œ 물리적인 뢀뢄에 λŒ€ν•΄μ„œλŠ” κ³ λ €ν•˜μ§€ μ•Šμ•„λ„ 됨!

Java Thread λž€?

  • Process

    : κ°œλ³„μ μœΌλ‘œ λ™μž‘ν•˜λŠ” ν”„λ‘œκ·Έλž¨ (Eclipse, Messenger, etc)

  • Thread

    : Processλ₯Ό κ΅¬μ„±ν•˜λŠ” μž‘μ€ μ‹€ν–‰ λ‹¨μœ„ (Messenger = chat + file transfer)

  • Multi-process

    : λ™μ‹œμ— μ—¬λŸ¬κ°œμ˜ processλ₯Ό μ‹€ν–‰ν•˜λŠ” 것

  • Multi-thread

    : ν•˜λ‚˜μ˜ processμ—μ„œ μ—¬λŸ¬κ°œμ˜ threadκ°€ λ™μ‹œμ— λ™μž‘ν•˜λŠ” 것

Java Thread 생성

방법 1) Runnable interface 생성

  • Runnable interface

    ex)

    package virus;
    
    public class CoronaRunnable implements Runnable{
    
    	int num;
    	public CoronaRunnable() {}
    	public CoronaRunnable(int num) {
    		this.num = num;
    	}
    	@Override
    	public void run() {
    		for (int i =0 ; i< 10000 ; i++) {
    			int j = i*100;
    		}
    		System.out.println(num);
    	}
    }

  • Test

    package app;
    
    import virus.CoronaRunnable;
    
    public class CoronaThreadTest {
    	public static void main(String[] args) {
    		for (int i = 0 ; i <1000 ; i++) {
    			CoronaRunnable cr = new CoronaRunnable(i);
    			Thread t = new Thread(cr);
    			// Thread λ™μž‘μ‹œν‚€κΈ°
    			t.start();
    		}
    	}
    }

방법 2) Thread class 생성

  • Thread class

    ex)

package virus;

public class CoronaThread extends Thread{ int num;

public CoronaThread() {}
public CoronaThread(int num) {
	this.num = num;
}

@Override
public void run() {
	for (int i = 0 ; i < 10000 ; i++) {
		int j = i*100;
	}
	System.out.println(num);
}

}


<br>

- Test

```java
import virus.CoronaRunnable;
import virus.CoronaThread;

public class CoronaThreadTest {
	public static void main(String[] args) {
		for (int i = 0 ; i <1000 ; i++) {
			CoronaThread ct = new CoronaThread(i);
			ct.start();
		}
	}
}

Thread μ‹€ν–‰ μ‹œ memory ꡬ쑰

Last updated