java多线程编程基础
2013-02-17 15:31
423 查看
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也有应用场景。
直接启动一个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也有应用场景。
相关文章推荐
- Java 多线程编程——Java多线程基础
- Java并发编程基础---(14)实现多线程的3种方式
- Java多线程编程基础之线程对象
- Java多线程程序设计入门-Java基础-Java-编程开发
- java多线程编程核心技术1-Thread基础知识
- java多线程编程基础
- Java基础知识强化之网络编程笔记05:UDP之多线程实现聊天室案例
- Java高并发编程之第一阶段,多线程基础深入浅出
- Java多线程编程总结笔记——一多线程基础知识
- java多线程编程基础
- 实战体会Java的多线程编程-Java基础-Java-编程开发
- java多线程编程基础(配合实例)
- java学习笔记14--多线程编程基础1
- Java多线程编程基础
- Java多线程编程核心技术读书笔记(1)-Thread基础
- Java多线程编程基础之线程对象
- Java多线程编程基础之线程对象
- 如何使用Java编写多线程程序-Java基础-Java-编程开发
- Java基础知识强化之网络编程笔记14:TCP之多个客户端上传到一个服务器的思考(多线程改进)
- java多线程基础学习-核心编程