Java中線程Thread的三種方式和對比
多線程主要的作用就是充分利用cpu的資源。單線程處理,在文件的加載的過程中,處理器就會(huì)一直處于空閑,但也被加入到總執(zhí)行時(shí)間之內(nèi),串行執(zhí)行切分總時(shí)間,等于每切分一個(gè)時(shí)間*切分后字符串的個(gè)數(shù),執(zhí)行程序,估計(jì)等幾分鐘能處理完就不錯(cuò)了。而多線程處理,文件加載與差分過程中
一、Java實(shí)現(xiàn)多線程的三種方式1.繼承Thread通過Thread繼承,并重寫run方法來實(shí)現(xiàn)多線程,案例如下:
public class ThreadPattern extends Thread { @Override public void run() {System.out.println('繼承Thread當(dāng)前執(zhí)行線程'+Thread.currentThread().getName()); }}// 測試public void threadTest() throws ExecutionException, InterruptedException {ThreadPattern pattern = new ThreadPattern();pattern.start(); }2.實(shí)現(xiàn)Runnable接口
Runable的實(shí)現(xiàn)類作為Thread的構(gòu)造參數(shù),來實(shí)現(xiàn)多線程,案例如下:
public class RunnablePattern implements Runnable{ @Override public void run() {System.out.println('實(shí)現(xiàn)Runnable方式,當(dāng)前執(zhí)行線程'+Thread.currentThread().getName()); }}// 測試public void runnableTest() throws ExecutionException, InterruptedException {RunnablePattern runnablePattern = new RunnablePattern();Thread thread = new Thread(runnablePattern);thread.start(); }3.實(shí)現(xiàn)Callable接口
實(shí)現(xiàn)Callable接口重寫call()方法,然后包裝成FutureTask,然后再包裝成Thread,其實(shí)本質(zhì)都是實(shí)現(xiàn)Runnable 接口。案例如下:
public class CallablePattern implements Callable { @Override public Object call() throws Exception {System.out.println('實(shí)現(xiàn)Callable方式,當(dāng)前執(zhí)行線程'+Thread.currentThread().getName());return '1'; }}// 測試public void callableTest() throws ExecutionException, InterruptedException {CallablePattern callablePattern = new CallablePattern();FutureTask<String> futureTask = new FutureTask<>(callablePattern);new Thread(futureTask).start(); }二、總結(jié)對三種使用方式的對比
1、Thread:繼承的方式,由于java的單一繼承機(jī)制。就無法繼承其他類,使用起來就不夠靈活。
2、Runnable:實(shí)現(xiàn)接口,比Thread類更加的靈活,沒有單一繼承的限制。
3、Callable:Thread和runnable都重寫run方法并且沒有返回值,Callable是重寫call()方法并且有返回值,借助FutureTask類來判斷線程是否執(zhí)行完畢或者取消線程執(zhí)行, 一般情況下不直接把線程體的代碼放在Thread類中,一般通過Thread類來啟動(dòng)線程。
4:Thread類實(shí)現(xiàn)Runnable ,Callable封裝成FutureTask,FutureTask實(shí)現(xiàn)RunnableFuture,RunnableFuture實(shí)現(xiàn)Runnable,所以Callable也算是一種Runnable,所以實(shí)現(xiàn)的方式本質(zhì)都是Runnable實(shí)現(xiàn)。
到此這篇關(guān)于Java中線程Thread的三種方式和對比的文章就介紹到這了,更多相關(guān)Java 線程Thread內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python excel和yaml文件的讀取封裝2. python如何實(shí)現(xiàn)word批量轉(zhuǎn)HTML3. 利用單元測試對PHP代碼進(jìn)行檢查4. python3實(shí)現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)5. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析6. moment轉(zhuǎn)化時(shí)間戳出現(xiàn)Invalid Date的問題及解決7. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊8. 如何對php程序中的常見漏洞進(jìn)行攻擊9. Python實(shí)現(xiàn)AES加密,解密的兩種方法10. 詳解Python利用configparser對配置文件進(jìn)行讀寫操作
