Java高并发之设计模式,设计思想
点击上方“码农突围”,马上关注
这里是码农充电第一站,回复“666”,获取一份专属大礼包 真爱,请设置“星标”或点个“在看
单例
懒汉式: 方法上加synchronized
public static synchronized Singleton getInstance() {
if (single == null) {
single = new Singleton();
}
return single;
}
懒汉式: 使用双检锁 + volatile
private volatile Singleton singleton = null;
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
懒汉式: 使用静态内部类
public class Singleton {
private static class LazyHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
饿汉式
public class Singleton1 {
private Singleton1() {}
private static final Singleton1 single = new Singleton1();
public static Singleton1 getInstance() {
return single;
}
}
Future模式
通过FutureTask实现
如果doOtherThing耗时2s, 则整个函数耗时2s左右.
如果doOtherThing耗时0.2s, 则整个函数耗时取决于RealData.costTime, 即1s左右结束.
public class FutureDemo1 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTaskfuture = new FutureTask (new Callable () {
@Override
public String call() throws Exception {
return new RealData().costTime();
}
});
ExecutorService service = Executors.newCachedThreadPool();
service.submit(future);
System.out.println("RealData方法调用完毕");
// 模拟主函数中其他耗时操作
doOtherThing();
// 获取RealData方法的结果
System.out.println(future.get());
}
private static void doOtherThing() throws InterruptedException {
Thread.sleep(2000L);
}
}
class RealData {
public String costTime() {
try {
// 模拟RealData耗时操作
Thread.sleep(1000L);
return "result";
} catch (InterruptedException e) {
e.printStackTrace();
}
return "exception";
}
}
通过Future实现
public class FutureDemo2 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService service = Executors.newCachedThreadPool();
Futurefuture = service.submit(new RealData2());
System.out.println("RealData2方法调用完毕");
// 模拟主函数中其他耗时操作
doOtherThing();
// 获取RealData2方法的结果
System.out.println(future.get());
}
private static void doOtherThing() throws InterruptedException {
Thread.sleep(2000L);
}
}
class RealData2 implements Callable<String>{
public String costTime() {
try {
// 模拟RealData耗时操作
Thread.sleep(1000L);
return "result";
} catch (InterruptedException e) {
e.printStackTrace();
}
return "exception";
}
@Override
public String call() throws Exception {
return costTime();
}
}
// 取消任务
boolean cancel(boolean mayInterruptIfRunning);
// 是否已经取消
boolean isCancelled();
// 是否已经完成
boolean isDone();
// 取得返回对象
V get() throws InterruptedException, ExecutionException;
// 取得返回对象, 并可以设置超时时间
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
生产消费者模式
生产者核心代码
while(isRunning) {
Thread.sleep(r.nextInt(SLEEP_TIME));
data = new PCData(count.incrementAndGet);
// 构造任务数据
System.out.println(data + " is put into queue");
if (!queue.offer(data, 2, TimeUnit.SECONDS)) {
// 将数据放入队列缓冲区中
System.out.println("faild to put data : " + data);
}
}
消费者核心代码
while (true) {
PCData data = queue.take();
// 提取任务
if (data != null) {
// 获取数据, 执行计算操作
int re = data.getData() * 10;
System.out.println("after cal, value is : " + re);
Thread.sleep(r.nextInt(SLEEP_TIME));
}
}
分而治之
Master-Worker模式
public class MasterDemo {
// 盛装任务的集合
private ConcurrentLinkedQueueworkQueue = new ConcurrentLinkedQueue ();
// 所有worker
private HashMapworkers = new HashMap<>();
// 每一个worker并行执行任务的结果
private ConcurrentHashMapresultMap = new ConcurrentHashMap<>();
public MasterDemo(WorkerDemo worker, int workerCount) {
// 每个worker对象都需要持有queue的引用, 用于领任务与提交结果
worker.setResultMap(resultMap);
worker.setWorkQueue(workQueue);
for (int i = 0; i < workerCount; i++) {
workers.put("子节点: " + i, new Thread(worker));
}
}
// 提交任务
public void submit(TaskDemo task) {
workQueue.add(task);
}
// 启动所有的子任务
public void execute(){
for (Map.Entryentry : workers.entrySet()) {
entry.getValue().start();
}
}
// 判断所有的任务是否执行结束
public boolean isComplete() {
for (Map.Entryentry : workers.entrySet()) {
if (entry.getValue().getState() != Thread.State.TERMINATED) {
return false;
}
}
return true;
}
// 获取最终汇总的结果
public int getResult() {
int result = 0;
for (Map.Entryentry : resultMap.entrySet()) {
result += Integer.parseInt(entry.getValue().toString());
}
return result;
}
}
public class WorkerDemo implements Runnable{
private ConcurrentLinkedQueueworkQueue;
private ConcurrentHashMapresultMap;
@Override
public void run() {
while (true) {
TaskDemo input = this.workQueue.poll();
// 所有任务已经执行完毕
if (input == null) {
break;
}
// 模拟对task进行处理, 返回结果
int result = input.getPrice();
this.resultMap.put(input.getId() + "", result);
System.out.println("任务执行完毕, 当前线程: " + Thread.currentThread().getName());
}
}
public ConcurrentLinkedQueuegetWorkQueue() {
return workQueue;
}
public void setWorkQueue(ConcurrentLinkedQueueworkQueue) {
this.workQueue = workQueue;
}
public ConcurrentHashMapgetResultMap() {
return resultMap;
}
public void setResultMap(ConcurrentHashMapresultMap) {
this.resultMap = resultMap;
}
}
public class TaskDemo {
private int id;
private String name;
private int price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
MasterDemo master = new MasterDemo(new WorkerDemo(), 10);
for (int i = 0; i < 100; i++) {
TaskDemo task = new TaskDemo();
task.setId(i);
task.setName("任务" + i);
task.setPrice(new Random().nextInt(10000));
master.submit(task);
}
master.execute();
while (true) {
if (master.isComplete()) {
System.out.println("执行的结果为: " + master.getResult());
break;
}
}
ForkJoin线程池
public class CountTask extends RecursiveTask<Long>{
// 任务分解的阈值
private static final int THRESHOLD = 10000;
private long start;
private long end;
public CountTask(long start, long end) {
this.start = start;
this.end = end;
}
public Long compute() {
long sum = 0;
boolean canCompute = (end - start) < THRESHOLD;
if (canCompute) {
for (long i = start; i <= end; i++) {
sum += i;
}
} else {
// 分成100个小任务
long step = (start + end) / 100;
ArrayListsubTasks = new ArrayList ();
long pos = start;
for (int i = 0; i < 100; i++) {
long lastOne = pos + step;
if (lastOne > end) {
lastOne = end;
}
CountTask subTask = new CountTask(pos, lastOne);
pos += step + 1;
// 将子任务推向线程池
subTasks.add(subTask);
subTask.fork();
}
for (CountTask task : subTasks) {
// 对结果进行join
sum += task.join();
}
}
return sum;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ForkJoinPool pool = new ForkJoinPool();
// 累加求和 0 -> 20000000L
CountTask task = new CountTask(0, 20000000L);
ForkJoinTaskresult = pool.submit(task);
System.out.println("sum result : " + result.get());
}
}
- END - 最近热文
• 武大94年博士年薪201万入职华为!学霸日程表曝光,简直降维打击! • 我在美团的八年 • 为什么下载小电影时,经常会卡在99%? • 朝阳群众盯上了望京A座?举报996造成交通严重堵塞
评论