java 多线程知识梳理4
常用并发辅助类 CountDownLatch Semaphore CyclicBarrier, 都基于ReentrantLock实现。
1 Semaphores are often used to restrict the number of threads than can
* access some (physical or logical) resource. For example, here is
* a class that uses a semaphore to control access to a pool of items:
Semaphores 信号量, 相对常规同步块只能有一个线程对资源进行操作,Semaphores能允许多个线程同时操作资源。
public
Semaphore(
int
permits) {
//参数permits表示许可数目,即同时可以允许多少线程进行访问
sync =
new
NonfairSync(permits);
}
public
Semaphore(
int
permits,
boolean
fair) {
//这个多了一个参数fair表示是否是公平的,即等待时间越久的越先获取许可
sync = (fair)?
new
FairSync(permits) :
new
NonfairSync(permits);
}
public
void
acquire()
throws
InterruptedException { }
//获取一个许可
public
void
acquire(
int
permits)
throws
InterruptedException { }
//获取permits个许可
public
void
release() { }
//释放一个许可
public
void
release(
int
permits) { }
//释放permits个许可
public
boolean
tryAcquire() { };
//尝试获取一个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
public
boolean
tryAcquire(
long
timeout, TimeUnit unit)
throws
InterruptedException { };
//尝试获取一个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false
public
boolean
tryAcquire(
int
permits) { };
//尝试获取permits个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
public
boolean
tryAcquire(
int
permits,
long
timeout, TimeUnit unit)
throws
InterruptedException { };
//尝试获取permits个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false
* private static final int MAX_AVAILABLE = 100;
* private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
*
* public Object getItem() throws InterruptedException {
* available.acquire();//允许前100个线程进入方法,之后的线程阻塞
* return getNextAvailableItem();
* }
*
* public void putItem(Object x) {
* if (markAsUnused(x))
* available.release();//是否一个许可,之后阻塞的线程可以调用getItem方法
* }
*
* // Not a particularly efficient data structure; just for demo
*
* protected Object[] items = ... whatever kinds of items being managed
* protected boolean[] used = new boolean[MAX_AVAILABLE];
*
* protected synchronized Object getNextAvailableItem() {
* for (int i = 0; i < MAX_AVAILABLE; ++i) {
* if (!used[i]) {
* used[i] = true;
* return items[i];
* }
* }
* return null; // not reached
* }
*
* protected synchronized boolean markAsUnused(Object item) {
* for (int i = 0; i < MAX_AVAILABLE; ++i) {
* if (item == items[i]) {
* if (used[i]) {
* used[i] = false;
* return true;
* } else
* return false;
* }
* }
* return false;
* }
*
* }
public
CountDownLatch(
int
count) { };
//参数count为计数值
public
void
await()
throws
InterruptedException { };
//调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
public
boolean
await(
long
timeout, TimeUnit unit)
throws
InterruptedException { };
//和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
public
void
countDown() { };
//将count值减1
public
class
Test {
public
static
void
main(String[] args) {
final
CountDownLatch latch =
new
CountDownLatch(
2
);
new
Thread(){
public
void
run() {
try
{
System.out.println(
"子线程"
+Thread.currentThread().getName()+
"正在执行"
);
Thread.sleep(
3000
);
System.out.println(
"子线程"
+Thread.currentThread().getName()+
"执行完毕"
);
latch.countDown();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
};
}.start();
new
Thread(){
public
void
run() {
try
{
System.out.println(
"子线程"
+Thread.currentThread().getName()+
"正在执行"
);
Thread.sleep(
3000
);
System.out.println(
"子线程"
+Thread.currentThread().getName()+
"执行完毕"
);
latch.countDown();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
};
}.start();
try
{
System.out.println(
"等待2个子线程执行完毕..."
);
latch.await();
System.out.println(
"2个子线程已经执行完毕"
);
System.out.println(
"继续执行主线程"
);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
public
CyclicBarrier(
int
parties, Runnable barrierAction) {//参数parties指让多少个线程或者任务等待至barrier状态;参数barrierAction为当这些线程都达到barrier状态时会执行的内容。
}
public
CyclicBarrier(
int
parties) {
}
public
int
await()
throws
InterruptedException, BrokenBarrierException { };//用来挂起当前线程,直至所有线程都到达barrier状态再同时执行后续任务;
public
int
await(
long
timeout, TimeUnit unit)
throws
InterruptedException,BrokenBarrierException,TimeoutException { };
* final int N;
* final float[][] data;
* final CyclicBarrier barrier;
*
* class Worker implements Runnable {
* int myRow;
* Worker(int row) { myRow = row; }
* public void run() {
* while (!done()) {
* processRow(myRow);
*
* try {
* barrier.await();//设置当前线程为barried状态,barrier内置的计数器+1,直到N
* } catch (InterruptedException ex) {
* return;
* } catch (BrokenBarrierException ex) {
* return;
* }
* }
* }
* }
*
* public Solver(float[][] matrix) {
* data = matrix;
* N = matrix.length;
* barrier = new CyclicBarrier(N,
* new Runnable() {//当N个线程处于barried状态后,执行后续的mergeRows任务。
* public void run() {
* mergeRows(...);
* }
* });
* for (int i = 0; i < N; ++i)
* new Thread(new Worker(i)).start();
* new Thread(new Worker(i)).start();
*
* waitUntilDone();
* }
* }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。