스레드(thread)
스레드
- 프로그램을 작성하다 보면 동시에 여러 개의 일을 해야 할 때가 있다
- 이러한 멀티 프로세싱을 구현할 수 있도록 제공하는 것이 스레드이다
스레드 작성 법
- 스레드를 작성하는 방법은 Thread 클래스를 상속받는 방법과 Runnable 인터페이스를 구현하는 방법 두 가지가 있다
클래스 상속 방법
- Thread 클래스를 상속받고 run 메서드를 구현해 주면 된다
class 클래스 이름 extends Thread{
public void run( ) {
소스코드
}
}
인터페이스 구현 법
- Runnable 인터페이스를 구현하고 run 메서드를 구현하면 된다
class 클래스 이름 implements Runnable{
public void run( ) {
소스코드
}
}
스레드 사용 법
- Thread 클래스를 상속받았을 경우에는 상속받은 클래스의 객체를 생성하고 start 메서드를 호출해준다
- interface를 사용할 경우에는 Thread 클래스의 객체를 생성하고 생성자에 인터페이스를 구현한 클래스의 객체를 넣어준다 그 이후에 start 메서드를 호출해준다
*Thread에는 Sleep이라는 메서드를 사용할 수 있음 인자 값으로 숫자를 적어주는데 100이라고 적어주면 100ms(millisecond, ms는 1000번에 1초)만큼 쉬었다가 진행
ThreadTest.java
--------------------------------------------------------------------------------------------------
Thread t1 = new Thread1( );
t1.start( );
Thread t2 = new Thread2( );
Thread t = new Thread(t2);
t.start( );
while(true) {
try {
Thread.sleep(1000);
}catch(Exception e) { }
System.out.print("*");
}
class Thread1 extends Thread{
public void run( ) {
while(true) {
try {
Thread.sleep(1000);
}catch(Exception e) { }
System.out.print("-");
}
}
}
class Thread2 implements Runnable{
@Override
public void run( ) {
// TODO Auto-generated method stub
while(true) {
try {
Thread.sleep(1000);
}catch(Exception e) { }
System.out.print("_");
}
}
}
--------------------------------------------------------------------------------------------------