라인을 만들고 시작하는 몇 가지 방법

1: 첫 번째 방법은 클래스를 Thread의 하위 클래스로 선언하는 것입니다.이 하위 클래스는 Thread 클래스의run 방법을 다시 쓴 다음run 방법에 해당하는 논리 코드를 기입해야 한다
class ThreadDemo1 extends Thread{
	@Override
	public void run() {
		
		for(int i =0;i<5;i++){
			
			System.out.println("Hello Thread"+i);
		}
	}
	
}
public class CreateThreadDemo {
	public static void main(String[] args) {
		ThreadDemo1 threadDemo1 = new ThreadDemo1();
		threadDemo1.start();
	}

}

둘째, 두 번째 방법은 Runnable 인터페이스를 실현하고run 방법을 작성하는 것이다. Thread 클래스를 계승하여 라인을 만드는 것보다 인터페이스를 실현하는 방식으로 라인을 만들면 클래스를 더욱 잘 확장할 수 있다. 이 클래스는 다른 클래스를 계승하여 자신의 수요를 확장할 수 있고 첫 번째 방식보다 더욱 유연하고 확장성이 강하다.
class ThreadDemo implements Runnable{
	@Override
	public void run() {
		
		for(int i =0;i<5;i++){
			
			System.out.println("Hello Thread"+i);
		}
	}
	
}
public class CreateThreadDemo {
	public static void main(String[] args) {
		Thread threadDemo1 = new Thread(new ThreadDemo());
		threadDemo1.start();
	}

}

3:Callable 인터페이스를 실현하는 루틴과 Runnable 인터페이스를 만드는 것은 다르다. 루틴이 실행된 후에 되돌아오는 값을 얻으려면Callable 인터페이스를 실현한다.
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class ThreadDemo implements Callable{

	@Override
	public String call() throws Exception {				
		return "Hello Callable";
	}
	
}
public class CreateThreadDemo {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		//            
		ExecutorService exec = Executors.newCachedThreadPool();
		Future submit = exec.submit(new ThreadDemo());
		//       
		String string = submit.get();
		System.out.println(string);
		
	}

}

좋은 웹페이지 즐겨찾기