Java Concurrency2

来源:互联网 发布:网络女王sm聊天室 编辑:程序博客网 时间:2024/06/05 19:06
java.util.concurrent.locks
Interface Lock
Lock 接口比Synchronized 关键字提供了更灵活方便的锁机制。取得锁和释放锁总是要成对出现。
Lock l = ...;l.lock();try { // access the resource protected by this lock} finally { l.unlock();}

boolean tryLock()

Acquires the lock if it is available and returns immediately with the value true. If the lock is not available then this method will return immediately with the value false.

void lock()

If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired.


java.util.concurrent.locks

Class ReentrantLock

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

isHeldByCurrentThread(): 当前线程是否持有锁

protected  Thread getOwner()

返回当前持有锁的线程

protected  Collection<Thread>  getQueuedThreads() 

返回等待持有锁的所有线程


java.util.concurrent
Interface Executor

这个接口只有一个方法:void execute(Runnable command)。有的Executor实现将command 放到现有Thread中执行,如: ThreadPool;有的Executor实现将command放入一个队列等待分配Thread去执行。


java.util.concurrent
Interface ExecutorService

继承Executor接口。

Future<?>  submit(Runnable task) 

与execute(Runnable command)方法类似;该方法还返回Future对象来描述传入的task. 


java.util.concurrent
Interface ScheduledExecutorService

继承ExecutorService,增加调度功能。


线程池Thread Pool

线程池与连接池的原理类似,消除了创建,销毁线程的开销。java.util.concurrent.Executors提供了几个工厂对象来创建线程池。

 static ExecutorService newFixedThreadPool(int nThreads) 

创建并返回一个线程池

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.


Fork/Join

Fork/Join实现了ExecutorService接口,最大限度的利用多核CPU。 Fork/Join使用一个线程池,Work-stealing 算法,空闲的线程能够从负担重的线程中“偷”负载。Fork/Join的核心是ForkJoinPool类,它能够执行ForkJoinTask。

Java 7引入。




0 0