Javaλ‘ λ€μ€ μ€λ λ λ§λ€κΈ°
λ€μ€ μ€λ λ λ§λ€κΈ°
볡μμ μ€λ λκ° μ€νλλ μν©μ μλ°λ‘ λ§λ€μ΄λ³΄μ.
Thread Class
extends Thread
νλμ μ€λ λλ₯Ό λ§λ€λ €λ©΄ Thread ν΄λμ€λ₯Ό extends νλ ν΄λμ€λ₯Ό λ§λ€μ΄μΌ νλ€.
run()
μ€λ λμ μ€ν λ΄μ©μ run() λ©μλ μμ λ€μ΄κ°μΌ νλ€.
thread.start()
ν΄λΌμ΄μΈνΈ κ°μ²΄κ° thread ν΄λμ€μ start() λ©μλλ₯Ό μ€ννλ©΄ μ€λ λκ° μ€νλλ€.
μμ
Light κ°μ²΄
Light κ°μ²΄κ° μλ€κ³ κ°μ νλ€.
Light κ°μ²΄λ ON
κ³Ό OFF
λ κ°μ§ μν μ€ νλμ΄κ³ , μ΅μ΄λ‘ μμ±λ Lightλ OFF
μνλΌκ³ νμ.ON
μνμμ on_button_pushed()
λ₯Ό μ€ννλ©΄ "λ°μ μμ"μ΄ μ½μ μ°½μ μΆλ ₯λκ³ , OFF
μνμμ on_button_pushed()
λ₯Ό μ€ννλ©΄ "Light On!" μ΄ μ€νλλ€κ³ νμ.
Thread1.java
class Thread1 extends Thread{
private Light light;
public void setLight(Light light) {
this.light = light;
}
public void run() {
try{
Thread.sleep(4000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("thread 1");
light.on_button_pushed();
System.out.println();
}
}
μ€ν ν Thread.sleep(4000)
μ μν΄ 4μ΄ λκΈ° ν light κ°μ²΄μ on_button_pushed()λ₯Ό μ€ννλ€.
Thread2.java
class Thread2 extends Thread{
private Light light;
public void setLight(Light light) {
this.light = light;
}
public void run() {
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("thread 2");
light.on_button_pushed();
System.out.println();
}
}
μ€ν ν Thread.sleep(1000)
μ μν΄ 1μ΄ λκΈ° ν light κ°μ²΄μ on_button_pushed()λ₯Ό μ€ννλ€.
Client
public class Main{
public static void main(String[] args) {
Light light = new Light();
Thread1 thread1 = new Thread1();
thread1.setLight(light);
Thread2 thread2 = new Thread2();
thread2.setLight(light);
thread1.start();
thread2.start();
}
}
thread1,2κ° light κ°μ²΄λ₯Ό 곡μ νλ€.
μΆλ ₯
thread 2
Light On!
thread 1
λ°μ μμ
thread2κ° 1μ΄ λκΈ°λ‘ λ¨Όμ μ€νλλ―λ‘ κ³΅μ νλ lightλ₯Ό ON μνλ‘ λ³κ²½νλ€.
thread1 μ
μ₯μμ lightκ° μ΄λ―Έ ONμ΄κΈ° λλ¬Έμ "λ°μ μμ"μ΄ μΆλ ₯λλ€.
μ°μ μμ
thread κ°μ μ°μ μμλ₯Ό setPriority
λ©μλλ‘ μ ν μ μλ€.
μ«μκ° λμμ§μλ‘ μ°μ μμκ° μ»€μ§λ€.
thread.setPriority(1);
thread.setPriority(10);
thread.setPriority(Thread.MAX_PRIORITY); // = 10
thread.setPriority(Thread.NORM_PRIORITY); // = 5
thread.setPriority(Thread.MIN_PRIORITY); // = 1