java多线程实现方法
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
編寫多線程程序是為了實(shí)現(xiàn)多任務(wù)的并發(fā)執(zhí)行,從而能夠更好地與用戶交互。一般有三種方法,Thread,Runnable,Callable.
Runnable和Callable的區(qū)別是,
(1)Callable規(guī)定的方法是call(),Runnable規(guī)定的方法是run().
(2)Callable的任務(wù)執(zhí)行后可返回值,而Runnable的任務(wù)是不能返回值得
(3)call方法可以拋出異常,run方法不可以
(4)運(yùn)行Callable任務(wù)可以拿到一個(gè)Future對(duì)象,表示異步計(jì)算的結(jié)果。它提供了檢查計(jì)算是否完成的方法,以等待計(jì)算的完成,并檢索計(jì)算的結(jié)果。通過Future對(duì)象可以了解任務(wù)執(zhí)行情況,可取消任務(wù)的執(zhí)行,還可獲取執(zhí)行結(jié)果。
1、通過實(shí)現(xiàn)Runnable接口來創(chuàng)建Thread線程:
? 步驟1:創(chuàng)建實(shí)現(xiàn)Runnable接口的類:?????
class SomeRunnable implements Runnable
{
??? public void run()
??? {
????? //do something here
??? }
}
步驟2:創(chuàng)建一個(gè)類對(duì)象:
?????? Runnable oneRunnable = new SomeRunnable();
步驟3:由Runnable創(chuàng)建一個(gè)Thread對(duì)象:
?????? Thread oneThread = new Thread(oneRunnable);
步驟4:啟動(dòng)線程:
??????? oneThread.start();
至此,一個(gè)線程就創(chuàng)建完成了。
注釋:線程的執(zhí)行流程很簡(jiǎn)單,當(dāng)執(zhí)行代碼oneThread.start();時(shí),就會(huì)執(zhí)行oneRunnable對(duì)象中的void run();方法,
該方法執(zhí)行完成后,線程就消亡了。
2、與方法1類似,通過實(shí)現(xiàn)Callable接口來創(chuàng)建Thread線程:其中,Callable接口(也只有一個(gè)方法)定義如下:
public interface Callable<V>??
{??
??? V call() throws Exception;??
}
步驟1:創(chuàng)建實(shí)現(xiàn)Callable接口的類SomeCallable<Integer>(略);
步驟2:創(chuàng)建一個(gè)類對(duì)象:
????? Callable<Integer> oneCallable = new SomeCallable<Integer>();
步驟3:由Callable<Integer>創(chuàng)建一個(gè)FutureTask<Integer>對(duì)象:
????? FutureTask<Integer> oneTask = new FutureTask<Integer>(oneCallable);
????? 注釋:FutureTask<Integer>是一個(gè)包裝器,它通過接受Callable<Integer>來創(chuàng)建,它同時(shí)實(shí)現(xiàn)了Future和Runnable接口。
?步驟4:由FutureTask<Integer>創(chuàng)建一個(gè)Thread對(duì)象:
?????? Thread oneThread = new Thread(oneTask);
步驟5:啟動(dòng)線程:
?????? oneThread.start();
至此,一個(gè)線程就創(chuàng)建完成了。
3、通過繼承Thread類來創(chuàng)建一個(gè)線程:
步驟1:定義一個(gè)繼承Thread類的子類:
class SomeThead extends Thraad
{
??? public void run()
??? {
???? //do something here
??? }
}
步驟2:構(gòu)造子類的一個(gè)對(duì)象:
????? SomeThread oneThread = new SomeThread();
步驟3:啟動(dòng)線程:
????? oneThread.start();
至此,一個(gè)線程就創(chuàng)建完成了。
?????? 注釋:這種創(chuàng)建線程的方法不夠好,主要是因?yàn)槠渖婕斑\(yùn)行機(jī)制問題,影響程序性能。
4、通過線程池來創(chuàng)建線程:
步驟1:創(chuàng)建線程池:
????? ExecutorService pool = Executors.newCachedThreadPool();
步驟2:通過Runnable對(duì)象或Callable對(duì)象將任務(wù)提交給ExecutorService對(duì)象:
????? Future<Integer> submit(Callable<Integer> task);
????? 注釋:Future是一個(gè)接口,它的定義如下:
public interface Future<T>
{
??? V get() throws ...;
??? V get(long timeout, TimeUnit unit) throws ...;
??? void cancle(boolean mayInterrupt);
??? boolean isCancelled();
??? boolean isDone();
}
????? 至此,一個(gè)線程就創(chuàng)建完成了。
????? 注釋:線程池需調(diào)用shutdown();方法來關(guān)閉線程。
轉(zhuǎn)載于:https://my.oschina.net/u/2000675/blog/619633
總結(jié)
以上是生活随笔為你收集整理的java多线程实现方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pymysql的相关操作
- 下一篇: Tiles Framework