Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- Reflex
- java정리
- 프로그래머스
- frontend
- 자바독학
- 코스닥
- 개발자
- Python
- 빅데이터
- 사물인터넷
- backend
- 자바정리
- 풀스택프레임워크
- 코딩
- 개발
- 코딩테스트
- 이웃한 칸
- 프로그래밍
- 백준
- 코테
- 주가예측
- 개인프로젝트
- java
- 자바
- 코딩독학
- Project
- 모의 주식
- 프로그램
- C++
- SNS
Archives
- Today
- Total
Creative Code
쓰레드 본문
**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.");
}
}