728x90
반응형
스레드(Thread)
한 프로세스 내에서 두가지 또는 그 이상의 일을 동시에 할 수 있다.
// Thread
public class Main extends Thread {
public void run() { // Thread를 상속하면 run 메서드를 구현해야한다.
while(true) {
System.out.println("thread run");
}
}
public static void main(String[] args) {
Main main = new Main();
main.start(); // start()로 쓰레드를 실행
Main m2 = new Main();
m2.start();
while(true) {
System.out.println("m");
}
}
}
Thread 예제
// Thread 예제
public class Main extends Thread {
int seq;
public Main(int seq) {
this.seq = seq;
}
public void run() {
System.out.println(this.seq+" thread start."); // 쓰레드 시작
try {
Thread.sleep(1000); // 1초 대기
} catch (Exception e) {}
System.out.println(this.seq + "Thread end."); // 쓰레드 종료
}
public static void main(String[] args) {
for(int i=0; i<10; i++) { // 총 10개의 쓰레드를 생성하여 실행
Thread t = new Main(i);
t.start();
}
System.out.println("main end."); // main 메서드 종료
}
}
728x90
반응형
'즐거운프로그래밍' 카테고리의 다른 글
[pandas] pandas Series 데이터 1 (0) | 2023.11.14 |
---|---|
[자바] 스레드(Thread) 예제 (0) | 2023.11.14 |
[자바] 예외(Exception) (0) | 2023.11.14 |
[자바] 싱글톤 패턴(singleton) (0) | 2023.11.14 |
[자바] 다형성(polymorphism) (0) | 2023.11.13 |