동작하고 있는 프로그램을 Process라고 함.
보통은 한 개의 Process가 하나의 업무을 처리하고 종료하지만 Thread를 이용하면 하나의 Process에서 여러개의 업무를 동시(병렬)에 처리 할 수 있다.
1. Thread 상속
ThreadExam01.java
public class ThreadExam01 extends Thread {
int seq;
public ThreadExam01(int seq){
this.seq = seq;
}
@Override
public void run() {
System.out.println(this.seq + " thread START");
try{
Thread.sleep(2000);
}catch(Exception ex){
ex.printStackTrace();
}
System.out.println(this.seq + " thread END");
}
}
ThreadMain01.java
public class ThreadMain01 {
public static void main(String[] args) {
try{
for(int i=0; i<10; i++){
Thread thread = new ThreadExam01(i);
thread.start();
}
}catch(Exception ex){
ex.printStackTrace();
}
System.out.println("ThreadMain01 END...");
}
}
결과
0 thread START
3 thread START
2 thread START
1 thread START
5 thread START
4 thread START
6 thread START
ThreadMain01 END...
7 thread START
9 thread START
8 thread START
4 thread END
8 thread END
7 thread END
9 thread END
2 thread END
3 thread END
6 thread END
1 thread END
5 thread END
0 thread END
2. Runnable 인터페이스 구현
ThreadExam02.java
public class ThreadExam02 implements Runnable {
int seq;
public ThreadExam02(int seq) {
this.seq = seq;
}
@Override
public void run() {
System.out.println(this.seq + " thread START");
try{
Thread.sleep(2000);
}catch(Exception ex){
ex.printStackTrace();
}
System.out.println(this.seq + " thread END");
}
}
ThreadMain02.java
public class ThreadMain02 {
public static void main(String[] args) {
try{
for(int i=0; i<10; i++){
Thread thread = new Thread(new ThreadExam02(i));
thread.start();
}
System.out.println("ThreadMain02 END");
}catch(Exception ex){
ex.printStackTrace();
}
}
}
결과
0 thread START
4 thread START
2 thread START
1 thread START
5 thread START
3 thread START
ThreadMain02 END
7 thread START
6 thread START
9 thread START
8 thread START
4 thread END
1 thread END
2 thread END
0 thread END
5 thread END
7 thread END
6 thread END
3 thread END
9 thread END
8 thread END
'프로그램 > Java & Jsp' 카테고리의 다른 글
[JAVA] 어노테이션 (Annotation) (0) | 2017.03.19 |
---|---|
[JAVA] Thread-2 (join) (0) | 2017.03.12 |
[JAVA] 열거 타입 (Enumeration Type) (0) | 2017.03.12 |
SHA-512 (Java, JavaScript 소스) (0) | 2013.02.07 |
[LIB] Search page (0) | 2013.02.06 |