1. 스레드
눈을 속일 수 있다. 왔다 갔다 굉장히 빠르게 하면 된다.
하나의 CPU가 두가지 일을 동시에 하는 것 → 멀티 스레드라고 한다.
자바는 스레드 하나만 가지고 있다 → 메인 스레드라고 한다.

2. 스레드 실습

package thread;
// SubThread -> Runnable (다형성)
class SubThread implements Runnable {
// 자바의 서브 메서드
@Override
public void run() {
for(int i=1; i<6; i++ ) {
try {
Thread.sleep(1000); // 1초
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("서브스레드 : " + i);
}
}
}
public class ThreadEx01 {
// 자바의 메인 스레드
public static void main(String[] args) {
SubThread st = new SubThread();
Thread t1 = new Thread(st); // 타겟을 선정
t1.start();
for(int i=1; i<6; i++ ) {
try {
Thread.sleep(1000); // 1초
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("메인스레드 : " + i);
}
}
}
Share article