前言
看多線程時,發現一些匿名內部類的東西,然后就來總結一下。
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 { public static 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; } }
4.線程定時任務
使用Timer類另起一個線程:
timer.schedule(TimerTask task, long delay, long period),第一個參數表示任務,第二個參數表示延遲時間,即啟動main方法后多久才會調用run方法的時間;第三個參數表示每隔多久重復執行run()方法,用等差數列表示,delay表示首項, period表示公差。
import java.util.Timer; import java.util.TimerTask; public class Demo1 { public static void main(String[] args) { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("start to run"); } },10000,1000); System.out.println("main thread"); } }
5.線程池
關於線程池的知識,暫不講解,只是做個demo。
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Demo2 { public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); for(int i =0;i<=100;i++){ executorService.execute(new Runnable(){ public void run() { System.out.println(Thread.currentThread().getName() + "正在執行"); } }); } }