Java 멀티스레드의 4가지 실현 방식

17187 단어 학습 노트
**
Java 멀티스레드의 4가지 실현 방식
**
1: Thread를 상속하고 런 방법을 다시 쓰고 start 방법을 호출합니다
/**
 * Java        1
 *   Thread ,  run  
 * @author hongbo.zhao 2019 4 12    7:12:35
 */
class MyThread extends Thread {
	
	@Override
	public void run() {
		//   thread       
		System.out.println(Thread.currentThread().getName());
	}
}

public class Demo03 {
	
	
	public static void main(String[] args) {
		
		for(int i=0;i<2;i++) {
			Thread t = new MyThread();
			//  :
			//Thread-0 Thread-1
			t.start();
		}
	}
}

2: Runnable 인터페이스를 실현하고 Thread를 초기화한 다음Thread 실례를 만들고 start 방법을 호출합니다
/**
 * Java        2
 *   Runnable  
 * @author hongbo.zhao 2019 4 12    7:12:35
 */
class MyThread implements Runnable {
	
	@Override
	public void run() {
		//   thread       
		System.out.println(Thread.currentThread().getName());
	}
}

public class Demo03 {
	
	
	public static void main(String[] args) {
		
		for(int i=0;i<2;i++) {
			Thread t = new Thread(new MyThread());
			//  :
			//Thread-0 Thread-1
			t.start();
		}
	}
}

3:Callable 인터페이스를 실현하고 Thread를 초기화한 다음Thread 실례를 만들고 start 방법을 호출합니다

/**
 * Java        3
 *   Callable  
 * @author hongbo.zhao 2019 4 12    7:12:35
 */
class MyThread implements Callable<Integer> {
	
	@Override
	public Integer call() throws Exception {
		System.out.println(Thread.currentThread().getName());
		return null;
	}
}

public class Demo03 {
	
	
	public static void main(String[] args) {
		
		for(int i=0;i<2;i++) {
			//  MyThread  
			Callable<Integer> c = new MyThread();
			//  FutureTask
			FutureTask<Integer> ft = new FutureTask<Integer>(c);
			//  FutureTask   Thread
			Thread t = new Thread(ft);
			//  :
			//Thread-0 Thread-1
			t.start();
		}
	}
}

4: 스레드 풀로 생성

/**
 * Java        4
 *    
 * @author hongbo.zhao 2019 4 12    7:12:35
 */
class MyThread implements Runnable {

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName());
	}
	
}

class MyThread2 implements Callable<Integer> {

	@Override
	public Integer call() throws Exception {
		System.out.println(Thread.currentThread().getName());
		return 0;
	}

	
}

public class Demo03 {
	
	
	public static void main(String[] args) {
		
		ExecutorService executorService = Executors.newFixedThreadPool(5);
		for(int i=0;i<2;i++) {
			executorService.execute(new MyThread());
			FutureTask<Integer> ft = new FutureTask<Integer>(new MyThread2());
			//  
//			pool-1-thread-1
//			pool-1-thread-2
//			pool-1-thread-3
//			pool-1-thread-4
			executorService.submit(ft);
		}
		executorService.shutdown();
	}
}

좋은 웹페이지 즐겨찾기