java多线程编程基础
thread和runnable已經(jīng)out了。取而代之的是callable<V>,它的結(jié)果存在future<V>中。后者有g(shù)et對象可以阻塞并最終獲得異步結(jié)果。FutureTask既是callable又是future。可以作為一個執(zhí)行單元。
直接啟動一個thread執(zhí)行callable是不明智的,因?yàn)樘嗟亩堂木€程會影響jvm的性能。較好的辦法是Executors的線程池。它有不同的方法創(chuàng)建不同的線程池:
newCachedThreadPool:New threads are created as needed; idle threads are kept
for 60 seconds.
newFixedThreadPool:The pool contains a fixed set of threads; idle threads are
kept indefinitely.
newSingleThreadExecutor:A “pool” with a single thread that executes the submitted
tasks sequentially (similar to the Swing event dispatch
thread).
newScheduledThreadPool:A fixed-thread pool for scheduled execution; a replacement
for java.util.Timer.
newSingleThreadScheduledExecutor:A single-thread “pool” for scheduled execution
當(dāng)你有了一個callable,你可以交給ExecutorService去執(zhí)行,通過submit。當(dāng)然runnable和thread也可以,不過他們沒有返回值。
?
如果你有一組task需要執(zhí)行,你不必一個一個的去啟動。ExecutorService的invokeAny和invokeAll可以幫你解決問題。你只需要處理返回的list<future>就可以了。ExecutorCompletionService是對ExecutorService的又一層封裝,可以幫助你依次獲得結(jié)果。
?
如果你的目的不只是利用多線程執(zhí)行一組任務(wù),而是需要多個線程互相協(xié)作,比如生產(chǎn)者-消費(fèi)者這樣的問題。那么需要進(jìn)行線程間的通訊。傳統(tǒng)的wait和notify已經(jīng)out了,await和signal用起來也比較麻煩。如果你的需求滿足一定的模式,那么java自帶哪些同步設(shè)施,比如CyclicBarrier,CountDownLatch,Exchanger,Semaphore,SychronousQueue可以滿足要求。具體的適用可以參見文檔。
?
如果線程需要訪問共享變量,那么java的同步集合是需要考慮得,其他的threadlocal也有應(yīng)用場景。
轉(zhuǎn)載于:https://www.cnblogs.com/alphablox/archive/2013/02/17/2914373.html
總結(jié)
以上是生活随笔為你收集整理的java多线程编程基础的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JSON 之 SuperObject(1
- 下一篇: 关于 win7 远程桌面的多用户问题