Notice
Recent Posts
Recent Comments
250x250
Creative Code
쓰레드 본문
728x90
**thread(동시실행) 실행방법
import java.util.ArrayList;
public class Main extends Thread {
int seq;
public Main(int seq) {
this.seq = seq;
}
public void run() { // 쓰레드를 사용하기위해서는 run()메서드를 사용해야한다.
System.out.println(this.seq + " thread start.");
try {
Thread.sleep(2000); // 쓰레드가 시작후 끝나기전까지 2초의 런타임을 둔다.
}catch (Exception e) {
}
System.out.println(this.seq+" thread end.");
}
public static void main(String[] args) {
ArrayList<Thread> threads = new ArrayList<>();
for (int i = 0; i<10; i++) {
Thread t = new Main(i);
t.start(); // 쓰레드를 시작하기위해서는 start()메서드를 사용해야한다.
threads.add(t);
}
for (int i = 0; i<threads.size(); i++) {
Thread t = threads.get(i);
try {
t.join(); // 쓰레드가 모두 끝날때까지 실행시킨다.
}catch(Exception e) {
}
}
System.out.println("main end.");
}
}
** thread 클래스를 상속하면 다른 클래스를 상속할수 없기 때문에 Runnable 인터페이스를 구현한다.
( Runnable 인터페이스는 Thread를 구현한다)
import java.util.ArrayList;
public class Main implements Runnable {
int seq;
public Main(int seq) {
this.seq = seq;
}
public void run() {
System.out.println(this.seq + " thread start.");
try {
Thread.sleep(2000);
}catch (Exception e) {
}
System.out.println(this.seq+" thread end.");
}
public static void main(String[] args) {
ArrayList<Thread> threads = new ArrayList<>();
for (int i = 0; i<10; i++) {
Thread t = new Thread(new Main(i));
t.start();
threads.add(t);
}
for (int i = 0; i<threads.size(); i++) {
Thread t = threads.get(i);
try {
t.join();
}catch(Exception e) {
}
}
System.out.println("main end.");
}
}
728x90