线程池:
//固定线程池,每次最多只能处理5个线程,其余的线程只能在池中等待
ExecutorService threadPool1 = Executors.newFixedThreadPool(5);
//缓存线程池,可管理的线程时可变的
ExecutorService threadPool2 = Executors.newCachedThreadPool();
//单个线程池,每次至少只运行一个线程,当里面的线程池中线程死掉死这个池就会再给你创建一个新的
ExecutorService threadPool3 = Executors.newSingleThreadExecutor();
其中ExecutorService继承了Executor接口,该接口只定义了一个方法
public interface Executor {
/**
* Executes the given command at some time in the future. The command
* may execute in a new thread, in a pooled thread, or in the calling
* thread, at the discretion of the <tt>Executor</tt> implementation.
*
* @param command the runnable task
* @throws RejectedExecutionException if this task cannot be
* accepted for execution.
* @throws NullPointerException if command is null
*/
void execute(Runnable command);
}
注意里面的参数是一个Runnable对象,所以execute就是表达线程池中的线程所要执行的run方法。一旦传入了这个重写run方法的Runnable对象后,从线程池中获取的线程就会去运行这个run方法
锁
Lock lock = new ReentrantLock();//定义一个锁
lock.lock();//上锁
lock.unlock();//解锁
一般要把unlock放在finally中
读写锁(多个读锁不互斥,写锁与读锁互斥,写锁与写锁互斥)
ReadWriteLock rwl = new ReentrantReadWriteLock();
rwl.readLock().lock();//上读锁
rwl.readLock().unlock();//解读锁
rwl.writeLock().lock();//上写锁
rwl.writeLock().unlock();//解写锁
条件
jdk中的一个实现缓冲区的例子
class BoundedBuffer {
final Lock lock = new ReentrantLock();//锁
final Condition notFull = lock.newCondition();//缓冲区没有满时的锁
final Condition notEmpty = lock.newCondition(); //缓冲区没有空时的锁
final Object[] items = new Object[100];//缓冲区可以存放100个Object
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();//上锁
try {
while (count == items.length) //当缓冲区满时,notFull等待
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;//防止数组越界
++count;//缓冲区数量加1
notEmpty.signal();//当缓冲区放入一个Object时发一个信号量通知notEmpty说可以往缓冲区取数据
} finally {
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();//上锁
try {
while (count == 0) //当缓冲区为空时,notEmpty等待
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;//防止数组越界
--count;//缓冲区数量减1
notFull.signal();//当缓冲区取走一个Object时发一个信号量通知notFull说可以往缓冲区放数据
return x;
} finally {
lock.unlock();
}
}
}
信号量Semaphore (维护了线程的访问数量)
Semaphore sp = new Semaphore(3);//声明了最多只能3个线程同时访问
sp.acquire()//线程获取一个认可,只有获取认可的线程才能往下执行,其余等待获取认可,直到有线程释放了认可(可以由另一个线程释放,不一定是获取认可的本线程)
sp.release()//释放一个认可
计数器CyclicBarrier
CyclicBarrier c = new CyclicBarrier(3);//创建了三个线程的计数器
c.await();//当所有的线程都执行到了await时才可以往下走
倒计时器CyclicDownLatch
CyclicDownLatch中的await方法可以让线程等待,直到另一个线程吧CyclicDownLatch归0
CyclicDownLatch中的countDown方法可以吧CyclicDownLatch归0,这时await的线程就可以放下执行