这里介绍的是 Semaphore类,CyclicBarrier类,Lock类
一、Semaphore类
Semaphore类是在多线程同时执行一段代码时,设置并发量并且保证在某一个线程执行完之后可以让后面线程进去执行
以下是代码样例,以供参考:
public static void main(String[] args) {
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
Semaphore semaphore = new Semaphore(3,true);
for (int i = 0; i < 20; i++) {
Runnable runnable = () -> {
try {
//获取资源访问
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程" + Thread.currentThread().getName() + "进入-当前有-" + (3 - semaphore.availablePermits()) + "个并发");
try {
Thread.sleep((long)(Math.random()*10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程--" + Thread.currentThread().getName() + "即将离开!");
//释放资源访问
semaphore.release();
};
newFixedThreadPool.execute(runnable);
}
newFixedThreadPool.shutdown();
}
二、CyclicBarrier类
CyclicBarrier类作用是用来等待线程线程全部到达之后才开始执行
代码样例:
public static void main(String[] args){
CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 20; i++) {
Runnable runnable = () -> {
try {
System.out.println("开始等待其他线程!");
cyclicBarrier.await();
System.out.println("执行线程!");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程执行完毕!");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
};
newFixedThreadPool.execute(runnable);
}
}
CyclicBarrier类代码的底层其实是用Lock锁实现的
三、Lock类
Lock类作用是被Lock锁住的地方单线程执行,后面的线程在阻塞队列等待当前线程执行完才可以再执行,下面是代码实例:
public static void main(String[] args) {
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(4);
Lock lock = new ReentrantLock();
for (int i = 0; i < 20; i++) {
Runnable runnable = () -> {
try {
lock.lock();
System.out.println("进入处理模块,当前线程是--" + Thread.currentThread().getName());
Thread.sleep((long) (Math.random() * 1000));
System.out.println("线程处理完成---" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
};
newFixedThreadPool.execute(runnable);
}
newFixedThreadPool.shutdown();
}