方法一:繼承Thread類創(chuàng)建線程
Java中實(shí)現(xiàn)多線程的一種方式是繼承Thread類。Thread類本質(zhì)上是實(shí)現(xiàn)了Runnable接口的一個(gè)實(shí)例,代表一個(gè)線程的實(shí)例。啟動(dòng)線程的唯一方法就是通過(guò)Thread類的start()方法。 通
Java中實(shí)現(xiàn)多線程的一種方式是繼承Thread類。Thread類本質(zhì)上是實(shí)現(xiàn)了Runnable接口的一個(gè)實(shí)例,代表一個(gè)線程的實(shí)例。啟動(dòng)線程的唯一方法就是通過(guò)Thread類的start()方法。
通過(guò)繼承Thread類并復(fù)寫(xiě)run()方法,我們可以自定義線程內(nèi)的操作邏輯。例如:
public class MyThread extends Thread { public void run() { ("()"); } } MyThread myThread1 new MyThread(); MyThread myThread2 new MyThread(); (); ();
方法二:實(shí)現(xiàn)Runnable接口創(chuàng)建線程
如果自己的類已經(jīng)繼承了其他類,則無(wú)法直接繼承Thread類。此時(shí),可以實(shí)現(xiàn)Runnable接口來(lái)創(chuàng)建線程。
public class MyThread extends OtherClass implements Runnable { public void run() { ("()"); } } MyThread myThread new MyThread(); Thread thread new Thread(myThread); ();
方法三:實(shí)現(xiàn)Callable接口通過(guò)FutureTask包裝器來(lái)創(chuàng)建線程
如果希望線程執(zhí)行完畢后返回結(jié)果,可以使用Callable接口配合FutureTask包裝器來(lái)創(chuàng)建線程。
public class SomeCallableextends OtherClass implements Callable { @Override public V call() throws Exception { // TODO Auto-generated method stub return null; } } Callable oneCallable new SomeCallable (); FutureTask oneTask new FutureTask (oneCallable); Thread oneThread new Thread(oneTask); ();
方法四:使用ExecutorService、Callable、Future實(shí)現(xiàn)有返回結(jié)果的線程
ExecutorService、Callable、Future是JDK中實(shí)現(xiàn)多線程的一套接口,其中Callable接口用于定義有返回值的任務(wù)。通過(guò)將Callable任務(wù)提交給ExecutorService線程池,并使用Future對(duì)象獲取任務(wù)的返回結(jié)果,就可以實(shí)現(xiàn)有返回結(jié)果的多線程。
import *; import ; import ; import ; @SuppressWarnings("unchecked") public class Test { public static void main(String[] args) throws ExecutionException, InterruptedException { ("----程序開(kāi)始運(yùn)行----"); Date date1 new Date(); int taskSize 5; ExecutorService pool (taskSize); List> list new ArrayList >(); for (int i 0; i < taskSize; i ) { Callable