Code&Data Insights

[ Java Programming ] Thread 본문

Computer Science/Java Programming

[ Java Programming ] Thread

paka_corn 2022. 4. 17. 06:13

[ Thread ]

- 한 프로세스 내에서 멀티 태스킹을 할 수 있도록 만들어진 프로세스를 스레드(Thread)라고 하며, 멀티 태스킹이 가능한 이유는  Multi Thread 때문이다. 

 

- A thread of execution in a program ( kind of like a virtual CPU )

 

- The JVM allows an application to have multiple threads running concurrently

 

- Each thread can execute parts of your code in parallel with the main thread

 

* Each thread has a priority ( 모든 쓰레드에는 각각 우선순위가 있다 ) 

-> Threads with higher priority are executed in preference compared to threads with a lower priority

--> 우선순위가 높은 스레드 먼저 실행, 낮은 스레드 순으로 실행된다 

-->  출력되는 순서를 예상할수 없다 ( 코드상으로 우선순위를 부여하지 않을 시 ) 

          => 스레드의 우선순위는 (1~10) , setPriority() 메서드를 사용해 우선순위 지정 가능 

          => 우선순위를 잘 지정하면, 스레드를 제어할 수 있다  

 

 

* The JVM(Java Virtual Machine) continues to execute threads until either of the following occurs

1) The exit method of class Runtime has been called

2) All user threads have died

 

* When a JVM starts up, there is a thread that calls the main methods

=> This thread is called " main ".

=> 모든 자바 어플리케이션은 Main Thread가 main() 메소드를 실행하면서 시작된다. 

 

* Daemon thread is a low priority thread that runs in the background to perform tasks such as garbage collection

JVM terminates itself when all user threads (non-daemon threads ) finish their execution. 

 

* < Thread를 실행하기 위한 2가지 방법 >

1. Thread를 상속해준 후 run() method를 overriding 한 후,  instance 할당 후 start() 메서드를 사용해 호출한다.

- If the class extends the Thread class, the thread can be run by creating an instance of the class and calling its start() method.

 

2. Runnable interface 구현하는 클래스를 작성 후, run() 메서드를 구현한다. 

- If the class implements the Runnable interface, the thread can be run by passing an instance of the class to a Thread object's constructor and then calling the thread's start() method.

 

 

Comments