상세 컨텐츠

본문 제목

Thread 의 생성 : Runnable 구현, Thread 상속

Java

by kwanghyup 2020. 6. 15. 19:05

본문

Thread 상속에 의한  방법 

// 쓰레드 생성  -  상속에 의한 방법
public class ThreadByExtends extends Thread{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(getName()); // 조상스레드 이름 출력
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } // try
        } //for
        System.out.println("Thread0 종료");
    } // run
}

 

Runnable 인터페이스 구현 

// 쓰레드 생성 :  Runnable 인터페이스를 구현
public class ThreadByRunnable implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            String name = Thread.currentThread().getName(); // 현재 스레드의 이름
            System.out.println(name);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } //try
        }//for
        System.out.println("Thread01 종료");
    }//run
}

 

생성된 스레드 실행 

public class ThreadStart {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = new ThreadByRunnable(); // Runnable 구현 객체 생성
        Thread thread2 = new Thread(runnable); // 스레드에 전달

        // 스레드를 상속한 객체 바로 생성
        ThreadByExtends thread1 = new ThreadByExtends();
        thread1.start(); // 스레드 동작 시작
        thread1.start();

        for (int i = 0; i < 100; i++) {
            String name = Thread.currentThread().getName(); // 메인스레드
            System.out.println(name);
            Thread.sleep(100);
        }// for end

        System.out.println("main 쓰레드 종료");
    }  //main end
}

 

관련글 더보기

댓글 영역