一種是繼承Thread類
一種實現Runnable接口多線程
public class Thread1 extends Thread { @Override public void run() { System.out.println("繼承Thread方式"); } public static void main(String[] args) { Thread1 thread = new Thread1(); thread.start(); } }
public class Thread2 implements Runnable { @Override public void run() { System.out.println("實現Runnable接口方式"); } public static void main(String[] args) { Runnable runnable = new Thread2(); Thread thread2 = new Thread(runnable); thread2.start(); } }
public class Thread3 implements Callable<String> { @Override public String call() throws Exception { Thread.sleep(5000); return "實現Callable方式,並經過FutureTask包裝,有返回值"; } public static void main(String[] args) throws ExecutionException, InterruptedException { Thread3 thread3 = new Thread3(); FutureTask futureTask = new FutureTask(thread3); Thread thread = new Thread(futureTask); thread.start(); System.out.println("線程已經啓動"); // 同步方式獲取返回結果 String result = (String) futureTask.get(); System.out.println(result); } }
匿名內部類也有多種變體,上述三種方式均可以使用匿名內部類來隱式實例化。ide
public class Demo{ public static void main(String[] args) throws Exception { //方式一:Thread匿名內部類 new Thread(){ @Override public void run() { // TODO Auto-generated method stub } }.start(); //方式二:Runnable匿名內部類 new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub } }).start(); ... } }
匿名內部類的優勢在於使用方便,不用額外定義類,缺點就是代碼可讀性差。線程
public class Demo{ public static void main(String[] args) throws Exception { new Thread(() -> System.out.println("running") ).start() ; ... } }
Runnable被@FunctionalInterface註解所修飾,而且接口中僅有一個方法code
public class DemoThreadTask implements Runnable{ @Override public void run() { // TODO Auto-generated method stub System.out.println("running"); } public static void main(String[] args) { DemoThreadTask task = new DemoThreadTask(); ExecutorService ex = Executors.newCachedThreadPool(); ex.execute(task); } }
public class DemoTimmerTask { public static void main(String[] args) throws Exception { Timer timer = new Timer(); timer.scheduleAtFixedRate((new TimerTask() { @Override public void run() { System.out.println("任務執行"); } }), 2000, 1000); } }
TimerTask的實現了Runnable接口,Timer內部有個TimerThread繼承自Thread。繼承