Creative Code

쓰레드 본문

코딩 study/JAVA

쓰레드

빛하루 2022. 7. 12. 22:53

**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.");
    }
}

'코딩 study > JAVA' 카테고리의 다른 글

자바 자료구조  (0) 2022.07.14
람다 함수,stream  (0) 2022.07.12
예외처리  (0) 2022.07.12
기타-(1)  (0) 2022.07.12
입출력  (0) 2022.07.12