线程唯一的单例

news/2025/2/11 22:35:54/

经典设计模式的单例模式是指进程唯一的对象实例,实现code如下:

package cun.zheng.weng.design.sinstnce;import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;public class IdGenerator {private IdGenerator(){}private AtomicLong generator = new AtomicLong(0);static class IdGeneratorHolder {private final static IdGenerator ID_GENERATOR = new IdGenerator();}public static IdGenerator getInstance(){return IdGeneratorHolder.ID_GENERATOR;}public Long getId(){return generator.getAndIncrement();}public static void main(String[] args) throws InterruptedException {ThreadPoolExecutor executor = new ThreadPoolExecutor(3,3,1000, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>());CountDownLatch latch = new CountDownLatch(10);for(int i=0;i<10;i++){Integer taskId = i;executor.submit(()->{Long threadId = Thread.currentThread().getId();System.out.println("Task "+ taskId +" generate id->" + IdGenerator.getInstance().getId() + " ,task done by "+ threadId);latch.countDown();});}latch.await();executor.shutdownNow();}
}输出结果:
Task 0 generate id->0 ,task done by 9
Task 1 generate id->1 ,task done by 10
Task 2 generate id->2 ,task done by 11
Task 3 generate id->3 ,task done by 9
Task 5 generate id->5 ,task done by 10
Task 4 generate id->4 ,task done by 11
Task 7 generate id->7 ,task done by 10
Task 6 generate id->6 ,task done by 9
Task 9 generate id->9 ,task done by 10
Task 8 generate id->8 ,task done by 11

别跟我扯什么双重检测单例模式,性能太差,不考虑,单例模式就用静态内部类实现,高性能+延迟加载,还要什么双重检测!

那么,问题来了,如果我要实现线程绑定呢,换句话说就是实现线程间唯一的单例,进程中可以有多个实例。

思路很简单:将线程id绑定对象实例就行了。以下使用Map和JDK原生的ThreadLocal实现这个想法。

package cun.zheng.weng.design.sinstnce;import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;public class ThreadSingleInstance {private ThreadSingleInstance(){}AtomicLong atomicLong = new AtomicLong(0);private static final Map<Long,ThreadSingleInstance> idGeneratorHolder = new ConcurrentHashMap<>();public Long getId(){return atomicLong.getAndIncrement();}public static ThreadSingleInstance getInstance(){Long threadId = Thread.currentThread().getId();idGeneratorHolder.putIfAbsent(threadId,new ThreadSingleInstance());return idGeneratorHolder.get(threadId);}public static void main(String[] args) throws InterruptedException {ThreadPoolExecutor executor = new ThreadPoolExecutor(3,3,1000, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>());CountDownLatch latch = new CountDownLatch(10);for(int i=0;i<10;i++){Integer taskId = i;executor.submit(()->{Long threadId = Thread.currentThread().getId();System.out.println("Task "+ taskId +" generate id->" + ThreadSingleInstance.getInstance().getId() + " ,task done by "+ threadId);latch.countDown();});}latch.await();executor.shutdownNow();}
}输出:
Task 1 generate id->0 ,task done by 10
Task 2 generate id->0 ,task done by 11
Task 3 generate id->1 ,task done by 10
Task 4 generate id->1 ,task done by 11
Task 5 generate id->2 ,task done by 10
Task 6 generate id->2 ,task done by 11
Task 7 generate id->3 ,task done by 10
Task 8 generate id->3 ,task done by 11
Task 9 generate id->4 ,task done by 10
Task 0 generate id->0 ,task done by 9

 

package cun.zheng.weng.design.sinstnce;import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;public class ThreadInstanceByThreadLocal {private ThreadInstanceByThreadLocal(AtomicLong atomicLong){this.atomicLong = atomicLong;}private AtomicLong atomicLong;public Long getId(){return atomicLong.getAndIncrement();}public static ThreadInstanceByThreadLocal getInstance(){return new ThreadInstanceByThreadLocal(new AtomicLong(0));}public static void main(String[] args) throws InterruptedException {ThreadPoolExecutor executor = new ThreadPoolExecutor(3,3,1000, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>());CountDownLatch latch = new CountDownLatch(10);ThreadLocal<ThreadInstanceByThreadLocal> threadLocal = new ThreadLocal<ThreadInstanceByThreadLocal>(){@Overrideprotected ThreadInstanceByThreadLocal initialValue() {return ThreadInstanceByThreadLocal.getInstance();}};for(int i=0;i<10;i++){Integer taskId = i;executor.submit(()->{Long threadId = Thread.currentThread().getId();System.out.println("Task "+ taskId +" generate id->" + threadLocal.get().getId() + " ,task done by "+ threadId);latch.countDown();});}latch.await();executor.shutdownNow();}
}


http://www.ppmy.cn/news/1080855.html

相关文章

Rust 学习笔记(持续更新中…)

一、 编译和运行是单独的两步 运行 Rust 程序之前必须先编译&#xff0c;命令为&#xff1a;rustc 源文件名 - rustc main.rs编译成功之后&#xff0c;会生成一个二进制文件 - 在 Windows 上还会生产一个 .pdb 文件 &#xff0c;里面包含调试信息Rust 是 ahead-of-time 编译的…

微信小程序地图应用总结版

1.应用场景&#xff1a;展示公司位置&#xff0c;并打开第三方app&#xff08;高德&#xff0c;腾讯&#xff09;导航到目标位置。 &#xff08;1&#xff09;展示位置地图 uniapp官网提供了相关组件&#xff0c;uniapp-map组件 具体用法&#xff1a; html结构 <map sty…

phpstorm配置链接sqlserver数据库

开启sqlserver的TCP/IP 1433端口

低成本32位单片机电动工具无感方波控制方案

RAMSUN介绍基于灵动32位微处理器MM32SPIN0230的BLDC电动工具无感方波控制方案&#xff0c;包括MM32SPIN0230芯片资源。 以下是电动工具无感方波控制方案的简述&#xff1a; MM32SPIN0230电动工具专用板 芯片介绍 MM32SPIN0230系列是灵动微MindSPIN旗下高性能的单电机控制产品…

微信小程序修改数据,input不能实时回显

场景&#xff1a; 填写发票抬头&#xff0c;填写抬头公司时候&#xff0c;会根据用户输入的内容实时获取相关的公司信息&#xff0c;用户选择搜索出来的公司&#xff0c;这时候 setData,但是数据并没有回显&#xff0c;而是需要再需要点一下屏幕。 解决方案&#xff1a; 原来…

从零开发JavaWeb入门项目--十天掌握

原文网址&#xff1a;从零开发JavaWeb入门项目--十天掌握_IT利刃出鞘的博客-CSDN博客 简介 这是一个靠谱的JavaWeb入门项目实战&#xff0c;名字叫蚂蚁爱购。从零开发项目&#xff0c;视频加文档&#xff0c;十天就能学会开发JavaWeb项目&#xff0c;教程路线是&#xff1a;搭…

selenium+find_elements用法

1、假如我们遇到多个标签的class一样&#xff0c;比如像下面这样的 我们可以采用js语法去定位&#xff0c;比如&#xff1a; document.getElementsByClassName("ant-calendar-picker-input ant-input")[0]

【前端】Layui动态数据表格拖动排序

目录 一、下载layui-soul-table 二、使用 三、Layui实际使用 1、html代码 2、JS代码 3、PHP后台代码 目的&#xff1a;使用Layui的数据表格&#xff0c;拖动行进行排序。 使用插件&#xff1a;layui-soul-table 和 Layui 1.layui-soul-table文档&#xff1a;https://…