多线程之创建线程有哪几种方式?
这个问题一般会出现在面试当中,多线程创建有哪几种方式呢?
答:实现Runable接口和实现Thread类。
我们先看看看实现这两种的实现方式
1 package com.summer; 2 3 public class ThreadA implements Runnable { 4 5 public void run() { 6 System.out.println("start ThreadA!"); 7 } 8 9 public static void main(String[] args) { 10 Thread thread = new Thread(new ThreadA()); 11 thread.start(); 12 } 13 }
1 package com.summer; 2 3 public class ThreadB extends Thread { 4 5 @Override 6 public void run() { 7 System.out.println("start ThreadB!"); 8 } 9 10 public static void main(String[] args) { 11 ThreadB threadB = new ThreadB(); 12 threadB.start(); 13 } 14 }
那么除了这两种方式以外还有什么其他方式呢?
答:可以实现Callable接口和线程池来创建线程。
1 package com.summer; 2 3 import java.util.concurrent.Callable; 4 import java.util.concurrent.FutureTask; 5 6 public class ThreadC implements Callable { 7 8 public Object call() throws Exception { 9 System.out.println("start ThreadC!"); 10 return null; 11 } 12 13 public static void main(String[] args) { 14 ThreadC threadC = new ThreadC(); 15 FutureTask futureTask = new FutureTask(threadC); 16 Thread thread = new Thread(futureTask); 17 thread.start(); 18 } 19 }
1 package com.summer; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 6 public class ThreadD implements Runnable { 7 8 public void run() { 9 System.out.println("start ThreadD!"); 10 } 11 12 public static void main(String[] args) { 13 ExecutorService executorService = Executors.newSingleThreadExecutor(); 14 executorService.execute(new ThreadD()); 15 } 16 }