【JAVA】執行緒建立和匿名內部類
阿新 • • 發佈:2018-12-23
前言
看多執行緒時,發現一些匿名內部類的東西,然後就來總結一下。
1.繼承Thread類
在類上實現匿名內部類
public class Demo1 { public static void main(String[] args) { Thread t = new Thread(){ @Override public void run() { System.out.println("This is the thread class"); } }; t.start(); } }
如果不用匿名內部類實現,則
public class Demo extends Thread { @Override public void run() { System.out.println("This is Thread class"); } public static void main(String[] args) { Demo demo = new Demo(); demo.start(); } }
2.實現Runnable介面
在介面上實現匿名內部類
public class Demo2 { publicstatic void main(String[] args) { Runnable r = new Runnable() { public void run() { System.out.println("this is Runnable interface"); } }; Thread t = new Thread(r); t.start(); } }
如果不用匿名內部類實現,則
public class Demo3 implements Runnable { public void run() { System.out.println("This is Rubanle interface"); } public static void main(String[] args) { Demo3 demo3 = new Demo3(); Thread t = new Thread(demo3); t.start(); } }
3.獲取有返回值的執行緒
使用Callable介面和FutureTask
import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; public class Demo2 implements Callable<Integer>{ public static void main(String[] args) throws Exception{ Demo2 d = new Demo2(); FutureTask<Integer> task = new FutureTask<Integer>(d); Thread t = new Thread(task); t.start(); System.out.println("我先乾點別的。。。"); Integer result = task.get(); System.out.println("執行緒執行的結果為:" + result); } public Integer call() throws Exception { System.out.println("正在進行緊張的計算"); Thread.sleep(3000); return 1; } }