java多线程编程基础

thread和runnable已经out了。取而代之的是callable<V>,它的结果存在future<V>中。后者有get对象可以阻塞并最终获得异步结果。FutureTask既是callable又是future。可以作为一个执行单元。

直接启动一个thread执行callable是不明智的,因为太多的短命的线程会影响jvm的性能。较好的办法是Executors的线程池。它有不同的方法创建不同的线程池:
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

当你有了一个callable,你可以交给ExecutorService去执行,通过submit。当然runnable和thread也可以,不过他们没有返回值。

如果你有一组task需要执行,你不必一个一个的去启动。ExecutorService的invokeAny和invokeAll可以帮你解决问题。你只需要处理返回的list<future>就可以了。ExecutorCompletionService是对ExecutorService的又一层封装,可以帮助你依次获得结果。

如果你的目的不只是利用多线程执行一组任务,而是需要多个线程互相协作,比如生产者-消费者这样的问题。那么需要进行线程间的通讯。传统的wait和notify已经out了,await和signal用起来也比较麻烦。如果你的需求满足一定的模式,那么java自带哪些同步设施,比如CyclicBarrier,CountDownLatch,Exchanger,Semaphore,SychronousQueue可以满足要求。具体的适用可以参见文档。

如果线程需要访问共享变量,那么java的同步集合是需要考虑得,其他的threadlocal也有应用场景。

原文地址:https://www.cnblogs.com/alphablox/p/2914373.html