轉自:http://my.oschina.net/dxf/blog/239
jdk1.5後,提供了java.util.concurrent包,它可以實現線程池,你把線程當成普通對象就可以了,它來負責調度和執行
包括兩類線程池
固定線程池
可變線程池
延遲線程池
固定線程池
public static ExecutorService newFixedThreadPool(int nThreads) 多任務
public static ExecutorService newSingleThreadPool() 單任務
ExecutorService 的方法
Excute(Runnablecommand);
shutdown();
用法如下
Mytask mt1=new Mytask("T1");//一個線程對象實例
ExecutorService threadpool=Executors.newFixedThreadPool(2);
threadpool.excute(mt1);
可變線程池
public static ExecutorService newCachedThreadPool()
延遲線程池,實現定時任務
public static ScheduledExecutorService newScheduledThreadPool(int poolSize)
它不使用excute方法了,而是使用schedule方法
public SchedualedFuture schedule(Runnable command,long delay,TimeUnit unit);
有返回值的線程池
Callable接口配合Future接口,Future接口用來接受返回值
Callable接口作用同runnable接口,不過它是實現call接口方法,這個方法還有返回值
class myCallableImpl implements Callable
{
public Object call()
{
}
}
使用
ExecutorService threadpool =Executors.newSingleThreadExector();
Future f=threadpool.submit(new myCallableImpl();
資源封鎖
前面我們知道syncnized方法可以對一段代碼進行資源封鎖,實際上還有很多其他方法,這裏總結一下
1:synchronized
2:變量volatile
3:lock接口的實現 ReentrantLock類,它有方法:lock()、unlock(),tryLock()等,注意要try……finally,防止死鎖
4:ReadWriteLock接口實現 ReentrantReadWriteLock類,方法爲readLock,writeLock,使用方法大致同lock接口,不過它的效率高。也要防止死鎖
5:信號量 Semaphore類,信號量不同於鎖,是用來實現資源分配的,但是也有鎖的特性,比如連接池,保證連接池不爆炸就可以使用這個類,主要方法爲:acquire(),acquire(int n),tryAcquire(),getQueueLength(),release()
6:原子對象,在jdk15後,爲了簡化操作,可以把一些基本類型定義爲原子對象,就單線程操作了。java.util.concurrent.atomic ,作用基本同變量volatile
7:障礙器,CyclicBarrier類,讓線程同步到同一個點
隊列和堆棧
java.util.Queue接口
public boolean offer(Object); 加入
public Object poll(); 出
peek(); 出,但是不刪除
remove();同poll
element();同peek
add();同offer
常見實現爲:java.util.LinkedList 和 java.util.PriorityQueue
BlockingQueue接口
java.util.concurrent.BlockingQueue
put(Object);進
take();出
BlockingDeque接口
它是一個阻塞的堆棧接口
putFirst(object o);
takeFirst();
putLast();
takeLast();