1.使用Unsafe类

import sun.misc.Unsafe;

class UnsafePackage {
private static Unsafe unsafe; static {
try {
Class<Unsafe> unsafeClass = Unsafe.class;
Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = (Unsafe) theUnsafe.get(null);
} catch (Exception ex) {
ex.printStackTrace();
}
} public static Unsafe getUnsafe() {
return unsafe;
}
}

2.声明简单锁

class CustomLock {
private volatile int status; private static Unsafe unsafe = UnsafePackage.getUnsafe();
private static long statusOffset;
private WaitingQueue queue = new WaitingQueue(); static {
try {
statusOffset = unsafe.objectFieldOffset(CustomLock.class.getDeclaredField("status"));
} catch (Exception ex) {
ex.printStackTrace();
}
} private boolean comareAndSetStatus(int originalStatus, int updateStatus) {
return unsafe.compareAndSwapInt(this, statusOffset, originalStatus, updateStatus);
} public boolean lock() {
if (comareAndSetStatus(0, 1)) {
//System.out.println("竞争锁成功!继续执行后面的代码");
return true;
} //System.out.println("竞争锁失败!进入等待队列");
push(Thread.currentThread());
while (!comareAndSetStatus(0, 1)) {
UnsafePackage.getUnsafe().park(false, 0);
}
return true;
} public boolean unlock() {
status = 0;
Thread thread = pop();
if (thread != null) {
UnsafePackage.getUnsafe().unpark(thread);
}
return true;
} private void push(Thread thread) {
queue.push(thread);
} private Thread pop() {
return queue.pop(); }
}

3.竞争锁失败的进队列

class WaitingQueue {
private volatile int status;
private static long statusOffset; /**
* 非线程安全,使用时,也要加锁
*/
private LinkedList<Thread> queue = new LinkedList<>(); static {
try {
statusOffset = UnsafePackage.getUnsafe().objectFieldOffset(WaitingQueue.class.getDeclaredField("status"));
} catch (Exception ex) {
ex.printStackTrace();
}
} public void push(Thread thread) {
while (!comareAndSetStatus(0, 1)) { }
queue.offerLast(thread);
comareAndSetStatus(1, 0);
return;
} public Thread pop() {
while (!comareAndSetStatus(0, 1)) { }
Thread elem = null;
if (!queue.isEmpty()) {
elem = queue.pop();
}
comareAndSetStatus(1, 0);
return elem;
} private boolean comareAndSetStatus(int originalStatus, int updateStatus) {
return UnsafePackage.getUnsafe().compareAndSwapInt(this, statusOffset, originalStatus, updateStatus);
}
}

3.调用如下

public class CustomLockTest {

    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
int threadCount = 1500;
CountDownLatch countDownLatch = new CountDownLatch(threadCount);
CustomLock lock = new CustomLock();
long start = System.currentTimeMillis();
IntStream.range(0, threadCount)
.forEach(p -> {
new Thread() {
@Override
public void run() {
lock.lock();
try {
for (int i = 0; i < 1000; i++) {
count++;
}
countDownLatch.countDown();
} finally {
lock.unlock();
}
}
}.start();
}); countDownLatch.await();
long end = System.currentTimeMillis();
System.out.println("结果值为:" + count + ",共花费了" + (end - start) + "毫秒!");
}
}
结果值为:1500000,共花费了601毫秒!

使用Unsafe来实现自定义锁的更多相关文章

  1. 【腾讯Bugly干货分享】浅谈Android自定义锁屏页的发车姿势

    本文来自于腾讯bugly开发者社区,非经作者同意,请勿转载,原文地址:http://dev.qq.com/topic/57875330c9da73584b025873 一.为什么需要自定义锁屏页 锁屏 ...

  2. 浅谈 Android 自定义锁屏页的发车姿势

    作者:blowUp,原文链接:http://mp.weixin.qq.com/s?__biz=MzA3NTYzODYzMg==&mid=2653577446&idx=2&sn= ...

  3. 重新想象 Windows 8.1 Store Apps (92) - 其他新特性: CoreDispatcher, 日历, 自定义锁屏系列图片

    [源码下载] 重新想象 Windows 8.1 Store Apps (92) - 其他新特性: CoreDispatcher, 日历, 自定义锁屏系列图片 作者:webabcd 介绍重新想象 Win ...

  4. 浅谈Android自定义锁屏页的发车姿势

    一.为什么需要自定义锁屏页 锁屏作为一种黑白屏时代就存在的手机功能,至今仍发挥着巨大作用,特别是触屏时代的到来,锁屏的功用被发挥到了极致.多少人曾经在无聊的时候每隔几分钟划开锁屏再关上,孜孜不倦,其酸 ...

  5. 模仿ReentrantLock类自定义锁

    简介 临近过年了,没什么需求,今天模仿ReentrantLock自定义写了一个自己锁,在这里记录一下,前提是对AQS原理有所了解,分享给大家 1.自定义锁MyLock package com.jack ...

  6. 自定义锁屏图片 win7

    win + R打开运行对话框 输入Regedit 点确定 进入注册表,找到以下项次 HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersi ...

  7. 005-多线程-锁-JUC锁-LockSupport【使用、Unsafe、对比Object的wait、底层源码】

    一.概述 在Java多线程中,当需要阻塞或者唤醒一个线程时,都会使用LockSupport工具类来完成相应的工作.LockSupport定义了一组公共静态方法,这些方法提供了最基本的线程阻塞和唤醒功能 ...

  8. c#自定义业务锁

    我们有这样的使用场景,某个订单在修改信息的时候,其他人不能修改相关的信息,比如不能做支付,不能退单等等,那么我们可以根据单号进行加锁,多Monitor做了如下扩展 定义接口 //// 文件名称:ILo ...

  9. 万字长文!从底层开始带你了解并发编程,彻底帮你搞懂java锁!

    线程是否要锁住同步资源 锁住 悲观锁 不锁住 乐观锁 锁住同步资源失败 线程是否要阻塞 阻塞 不阻塞自旋锁,适应性自旋锁 多个线程竞争同步资源的流程细节有没有区别 不锁住资源,多个线程只有一个能修改资 ...

随机推荐

  1. 阿里云ECS无法通过SSL远程链接问题。

    自己配置的SSL,通过密码,公司的是通过密钥,结果也是一样, 环境:centos7.x 网络: 家里宽带 公司网络 省图书馆wifi 家里宽带,公司网络均可以链接上去, 但唯独省图书馆wifi链接失败 ...

  2. 《Tomcat权威指南》读书笔记

    第一章 Tomcat的开幕式 1.Tomcat是以Java编写的,这表示在能够构建和测试它之前,必须安装最新的.完整的JAVA运行环境(JRE,Java runtime). 2.Catalina To ...

  3. Test 6.24 T3 水题

    问题描述 秋之国首都下了一场暴雨,由于秋之国地势高低起伏,不少地方出现了积水. 秋之国的首都可以看成一个 n 行 m 列的矩阵,第 i 行第 j 列的位置高度为 ai,j,首都以外的地方的高度可以都看 ...

  4. poj 3468 : A Simple Problem with Integers 【线段树 区间修改】

    题目链接 题目是对一个数组,支持两种操作 操作C:对下标从a到b的每个元素,值增加c: 操作Q:对求下标从a到b的元素值之和. #include<cstdio> #include<c ...

  5. swagger2接口发布demo

    1.目的:使用Swagger2发布接口,ui可操作 2.项目结构  3. 代码 3.1 接口类qinfeng.zheng.api.controller.DemoController package q ...

  6. java连接redis5.0单机版报连接超时错误

    使用java代码测试redis5.0单机版时,报redis连接超时异常,而linux上的redis能正常访问: redis.clients.jedis.exceptions.JedisConnecti ...

  7. 【HDOJ6628】permutation 1(dfs)

    题意:求1到n的排列中使得其差分序列的字典序为第k大的原排列 n<=20,k<=1e4 思路:爆搜差分序列,dfs时候用上界和下界剪枝 #include<bits/stdc++.h& ...

  8. curry柯里化

    Function.prototype.method = function(name,func){ if(!this.prototype[name]){ this.prototype[name] = f ...

  9. MySQL部分索引

    部分索引 char/varchar2太长,全部做索引的话,效率低,浪费存储空间 select avg(length(username)) from 索引统计: show index from tabl ...

  10. python安装centos7

    1.安装git (需root权限) yum -y install git 2.安装依赖包 yum -y install gcc make patch gdbm-devel openssl-devel ...