본문으로 바로가기

쓰레드 생성,동기화

category 프로그래밍/java 2017. 9. 14. 11:50

쓰레드 생성하기(또 다른 방법)


지금까지 스레드를 생성할 때 Thread 클래스를 확장한 클래스를 사용했습니다. 
그런데 Thread 클래스를 상속받을 클래스가 이미 다른 클래스를 상속받았을 경우에는 

두개 이상의 클래스로부터 상속받을 수 없다. 


//class Car extends Vehicle, Material

이럴 때 클래스 라이브러리의 Runnable 인터페이스(java.lang 패키지)를 사용하면 스레드로 만들 수 있는 클래스를 만들 수 있다. 

즉, Thread 클래스를 확장하는 것이 아니라 Runnable 인터페이스를 구현하는 것이다. 


class Car extends Vehicle implements Runable


sample6.java


class Car implements Runnable Runnable implements 인터페이스를 구현한다. 

{

private String name;

public Car(String nm)

{

name = nm;

}

public void run()

{

for(int i=0; i<5; i++)

{

System.out.println(name +"가 동작하고 있습니다.");

}

}

}

public class Sample6 {


public static void main(String[] args) {

// TODO Auto-generated method stub

Car car1 = new Car("1호차"); Thread 클래스의 객체를 생성한다.

Thread thi = new Thread(car1); 스레드를 기동시킨다. 

thi.start();

for(int i = 0; i<5; i++)

{

System.out.println("main() 메소드 실행중입니다.");

}

}


}


main()메소드에서 Car클래스의 객체를 생성

Thread 클래스의 객체를 생성한 다음 start() 메소드를 호출

'프로그래밍 > java' 카테고리의 다른 글

애플릿(애플릿, 애플릿 뷰어)  (1194) 2017.09.16
동기화  (1036) 2017.09.15
스레드(스레드 기동, 스레드 일시정지)  (1195) 2017.09.12
예외 및 입출력 처리  (1216) 2017.09.11
대규모 프로그램사용(파일분할, 패키지, 임포트)  (1197) 2017.09.08