Java Application

Java Thread - from Java Tutorials - 자바쓰레드 만들기 기초

wowbelly 2012. 5. 18. 10:02

자바쓰레드 구현 방법 2가지

 

Runnable 인터페이스 구현:

A runnable object defines an actual task that is to be executed.

It doesn't define how it is to be executed.

Runnable is actually an interface, with the single run() method that we must provide.

 

Thread 클래스 상속:

A Java Thread object wraps around an actual thread of execution.

It effectively defines how the task is to be executed - namely, at the same time as other threads.

To run the task defined, we create a Thread object for each Runnable, then call the start() method on each Thread.

 

 

 

1. Runnable 인터페이스 구현(일반적임, 클래스를 상속할 수 있슴)

 - Runnable 객체를 Thread 생성자에 전달하여 쓰레드 생성함

 

public class HelloRunnable implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }

}

 

 

 

 

2. Thread 클래스 상속

(클래스상속할 수 없슴; 이미 Thread클래스를 상속함; 자바클래스는 두 개 이상의 클래스를 상속할 수 없슴)


public class HelloThread extends Thread {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }

}

 

 

출처: http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

출처: http://www.javamex.com/tutorials/threads/