使用synchronized实现一个Lock代码详解

刚看到这个题目的时候无从下手,因为觉得synchronized和lock在加锁的方式上有很大不同,比如,看看正常情况下synchronized时如何加锁的。

方式一:

public synchronized void a(){
  //TODO
} 

方式二:

public void b(){
  synchronized(this){
    //TODO
  }
} 

从这两种方式来看,锁都是加在{}之间的,我们再来看看Lock是如何做的呢:

public void c() {
  lock.lock();
  try {
    // TODO
  } finally {
    lock.unlock();
  }
} 

这种方式的锁是加在lock()和unlock()之间的,所以要想实现一个lock功能,就要想怎么实现这样两个方法,lock()和unlock()方法,先定义一个框架如下所示:

public void lock(){
}
public void unlock(){
}

然后要想怎么用synchronized去实现这两个方法。

现在其实只是稍微清楚了一点思路,但是还不知道怎么去填充这两个方法,这是后再来分析一下Lock的加锁有什么特点,再来看看这段代码:

public void c() {
	lock.lock();
	//When current thread get the lock, other thread has to wait
	try {
		//current thread get in the lock, other thread can not get in
		// TODO
	}
	finally {
		lock.unlock();
		//current thread release the lock
	}
}

这段代码我只是加了一点注释,别的什么都没有做,是不是帮助理解这段代码,看看出现频率最高的词是什么,是currentthread,那么我们去填充lock()和unlock()方法的时候是不是注意要抓住currentthread这个关键字就可以找到解决方案呢?答案是肯定的。

接着分析,使用synchronized的时候如何让线程等待呢?是用wait()方法。怎么让线程唤醒呢,是用notify()方法。那么就要在lock()方法中使用wait()方法,在unlock()方法中使用notify()方法。那么我们在使用wait()和notify()的时候是有一个条件的,想想我们应该使用什么作为条件呢?

我们应该使用当前锁是否被占用作为判断条件,如果锁被占用,currentthread等待,想想我们在使用synchronized的时候是不是一直使用的这个条件,答案也是肯定的。

再来分析一下什么时候释放锁,使用什么作为条件,想想如果线程A拿到了锁,线程B能释放吗?当然不能,如果B能释放就违反了原则,当然不能。肯定是A线程的锁只能A来释放。所以判断条件就是判断持有锁的线程是不是currentthread,如果是的话,可以释放,不是的话当然不能。

现在来看看完整的代码:

package test.lock;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class NaiveLock {
	private static final long NONE = -1;
	private long owner = NONE;
	private Boolean isLooked() {
		return owner != NONE;
	}
	public synchronized void lock() {
		long currentThreadId = Thread.currentThread().getId();
		if (owner == currentThreadId) {
			throw new IllegalStateException("Lock has been acquired by current thread");
		}
		while (this.isLooked()) {
			System.out.println(String.format("thread %s is waitting lock", currentThreadId));
			try {
				wait();
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		owner = currentThreadId;
		System.out.println(String.format("Lock is acquired by thread %s", owner));
	}
	public synchronized void unlock() {
		if (!this.isLooked() || owner != Thread.currentThread().getId()) {
			throw new IllegalStateException("Only Lock owner can unlock the lock");
		}
		System.out.println(String.format("thread %s is unlocking", owner));
		System.out.println();
		owner = NONE;
		notify();
	}
	public static void main(String[] args) {
		final NaiveLock lock = new NaiveLock();
		ExecutorService executor = Executors.newFixedThreadPool(20, new ThreadFactory() {
			private ThreadGroup group = new ThreadGroup("test thread group");
			{
				group.setDaemon(true);
			}
			@Override
			      public Thread newThread(Runnable r) {
				return new Thread(group, r);
			}
		}
		);
		for (int i = 0; i < 20; i++) {
			executor.submit(new Runnable() {
				@Override
				        public void run() {
					lock.lock();
					System.out.println(String.format("thread %s is running...", Thread.currentThread().getId()));
					try {
						Thread.sleep(new Random().nextint(1000));
					}
					catch (InterruptedException e) {
						e.printStackTrace();
					}
					lock.unlock();
				}
			}
			);
		}
	}
}

运行一下看看结果:

Lock is acquired by thread 8
thread 8 is running...
thread 27 is waitting lock
thread 26 is waitting lock
thread 25 is waitting lock
thread 24 is waitting lock
thread 23 is waitting lock
thread 22 is waitting lock
thread 21 is waitting lock
thread 20 is waitting lock
thread 19 is waitting lock
thread 18 is waitting lock
thread 17 is waitting lock
thread 16 is waitting lock
thread 15 is waitting lock
thread 14 is waitting lock
thread 13 is waitting lock
thread 12 is waitting lock
thread 11 is waitting lock
thread 10 is waitting lock
thread 9 is waitting lock
thread 8 is unlocking 

Lock is acquired by thread 27
thread 27 is running...
thread 27 is unlocking 

Lock is acquired by thread 26
thread 26 is running...
thread 26 is unlocking 

Lock is acquired by thread 25
thread 25 is running...
thread 25 is unlocking 

Lock is acquired by thread 24
thread 24 is running...
thread 24 is unlocking 

Lock is acquired by thread 23
thread 23 is running...
thread 23 is unlocking 

Lock is acquired by thread 22
thread 22 is running...
thread 22 is unlocking 

Lock is acquired by thread 21
thread 21 is running...
thread 21 is unlocking 

Lock is acquired by thread 20
thread 20 is running...
thread 20 is unlocking 

Lock is acquired by thread 19
thread 19 is running...
thread 19 is unlocking 

Lock is acquired by thread 18
thread 18 is running...
thread 18 is unlocking 

Lock is acquired by thread 17
thread 17 is running...
thread 17 is unlocking 

Lock is acquired by thread 16
thread 16 is running...
thread 16 is unlocking 

Lock is acquired by thread 15
thread 15 is running...
thread 15 is unlocking 

Lock is acquired by thread 14
thread 14 is running...
thread 14 is unlocking 

Lock is acquired by thread 13
thread 13 is running...
thread 13 is unlocking 

Lock is acquired by thread 12
thread 12 is running...
thread 12 is unlocking 

Lock is acquired by thread 11
thread 11 is running...
thread 11 is unlocking 

Lock is acquired by thread 10
thread 10 is running...
thread 10 is unlocking 

Lock is acquired by thread 9
thread 9 is running...
thread 9 is unlocking 

如果把for循环改成30次,再看一下结果:

Lock is acquired by thread 8
thread 8 is running...
thread 27 is waitting lock
thread 26 is waitting lock
thread 25 is waitting lock
thread 24 is waitting lock
thread 23 is waitting lock
thread 22 is waitting lock
thread 21 is waitting lock
thread 20 is waitting lock
thread 19 is waitting lock
thread 18 is waitting lock
thread 17 is waitting lock
thread 16 is waitting lock
thread 15 is waitting lock
thread 14 is waitting lock
thread 13 is waitting lock
thread 12 is waitting lock
thread 11 is waitting lock
thread 10 is waitting lock
thread 9 is waitting lock
thread 8 is unlocking 

Lock is acquired by thread 27
thread 27 is running...
thread 8 is waitting lock
thread 27 is unlocking 

Lock is acquired by thread 27
thread 27 is running...
thread 26 is waitting lock
thread 27 is unlocking 

Lock is acquired by thread 27
thread 27 is running...
thread 25 is waitting lock
thread 27 is unlocking 

Lock is acquired by thread 24
thread 24 is running...
thread 27 is waitting lock
thread 24 is unlocking 

Lock is acquired by thread 23
thread 23 is running...
thread 24 is waitting lock
thread 23 is unlocking 

Lock is acquired by thread 22
thread 22 is running...
thread 23 is waitting lock
thread 22 is unlocking 

Lock is acquired by thread 22
thread 22 is running...
thread 21 is waitting lock
thread 22 is unlocking 

Lock is acquired by thread 22
thread 22 is running...
thread 20 is waitting lock
thread 22 is unlocking 

Lock is acquired by thread 22
thread 22 is running...
thread 19 is waitting lock
thread 22 is unlocking 

Lock is acquired by thread 22
thread 22 is running...
thread 18 is waitting lock
thread 22 is unlocking 

Lock is acquired by thread 17
thread 17 is running...
thread 17 is unlocking 

Lock is acquired by thread 16
thread 16 is running...
thread 16 is unlocking 

Lock is acquired by thread 15
thread 15 is running...
thread 15 is unlocking 

Lock is acquired by thread 14
thread 14 is running...
thread 14 is unlocking 

Lock is acquired by thread 13
thread 13 is running...
thread 13 is unlocking 

Lock is acquired by thread 12
thread 12 is running...
thread 12 is unlocking 

Lock is acquired by thread 11
thread 11 is running...
thread 11 is unlocking 

Lock is acquired by thread 10
thread 10 is running...
thread 10 is unlocking 

Lock is acquired by thread 9
thread 9 is running...
thread 9 is unlocking 

Lock is acquired by thread 8
thread 8 is running...
thread 8 is unlocking 

Lock is acquired by thread 26
thread 26 is running...
thread 26 is unlocking 

Lock is acquired by thread 25
thread 25 is running...
thread 25 is unlocking 

Lock is acquired by thread 27
thread 27 is running...
thread 27 is unlocking 

Lock is acquired by thread 24
thread 24 is running...
thread 24 is unlocking 

Lock is acquired by thread 23
thread 23 is running...
thread 23 is unlocking 

Lock is acquired by thread 21
thread 21 is running...
thread 21 is unlocking 

Lock is acquired by thread 20
thread 20 is running...
thread 20 is unlocking 

Lock is acquired by thread 19
thread 19 is running...
thread 19 is unlocking 

Lock is acquired by thread 18
thread 18 is running...
thread 18 is unlocking 

总结

以上就是本文关于使用synchronized实现一个Lock代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

Java线程同步Lock同步锁代码示例

Java编程synchronized与lock的区别【推荐】

Java多线程之readwritelock读写分离的实现代码

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

(0)

相关推荐

  • 简单了解synchronized和lock的区别

    这篇文章主要介绍了简单了解synchronized和lock的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 类别 synchronized Lock 存在层次 Java的关键字 一个类 锁的释放 1.以获取锁的线程执行代码同步代码,释放锁. 2,线程执行发生异常,jvm会让线程释放锁 在finally中必须释放锁,不然容易造成线程死锁 锁的获取 假设A线程获得锁,B线程等待,如果A线程阻塞,则B会一直等 分情况而定,Lock有多个获取锁的

  • 透彻理解Java中Synchronized(对象锁)和Static Synchronized(类锁)的区别

    本文讲述了Java中Synchronized(对象锁)和Static Synchronized(类锁)的区别.分享给大家供大家参考,具体如下: Synchronized和Static Synchronized区别 通过分析这两个用法的分析,我们可以理解java中锁的概念.一个是实例锁(锁在某一个实例对象上,如果该类是单例,那么该锁也具有全局锁的概念),一个是全局锁(该锁针对的是类,无论实例多少个对象,那么线程都共享该锁).实例锁对应的就是synchronized关键字,而类锁(全局锁)对应的就是

  • Java编程synchronized与lock的区别【推荐】

    前言 本文介绍了Java编程synchronized与lock的区别的相关内容,如果您对synchronized与lock不太了解,这两篇文章 或许是不错的选择: Java 同步锁(synchronized)详解及实例 Java多线程基础--Lock类 正文 从Java 5之后,在java.util.concurrent.locks包下提供了另外一种方式来实现同步访问,那就是Lock. 也许有朋友会问,既然都可以通过synchronized来实现同步访问了,那么为什么还需要提供Lock?这个问题

  • 深入Synchronized和java.util.concurrent.locks.Lock的区别详解

    主要相同点:Lock能完成Synchronized所实现的所有功能.主要不同点:Lock有比Synchronized更精确的线程予以和更好的性能.Synchronized会自动释放锁,但是Lock一定要求程序员手工释放,并且必须在finally从句中释放.synchronized 修饰方法时 表示同一个对象在不同的线程中 表现为同步队列如果实例化不同的对象 那么synchronized就不会出现同步效果了.1.对象的锁 所有对象都自动含有单一的锁. JVM负责跟踪对象被加锁的次数.如果一个对象被

  • 深入理解java内置锁(synchronized)和显式锁(ReentrantLock)

    synchronized 和 Reentrantlock 多线程编程中,当代码需要同步时我们会用到锁.Java为我们提供了内置锁(synchronized)和显式锁(ReentrantLock)两种同步方式.显式锁是JDK1.5引入的,这两种锁有什么异同呢?是仅仅增加了一种选择还是另有其因?本文为您一探究竟. // synchronized关键字用法示例 public synchronized void add(int t){// 同步方法 this.v += t; } public stati

  • 详谈Lock与synchronized 的区别

    1.lock是可中断锁,而synchronized 不是可中断锁 线程A和B都要获取对象O的锁定,假设A获取了对象O锁,B将等待A释放对O的锁定, 如果使用 synchronized ,如果A不释放,B将一直等下去,不能被中断 如果 使用ReentrantLock,如果A不释放,可以使B在等待了足够长的时间以后,中断等待,而干别的事情 ReentrantLock获取锁定与三种方式: a)  lock(),如果获取了锁立即返回,如果别的线程持有锁,当前线程则一直处于休眠状态,直到获取锁 b) tr

  • 使用synchronized实现一个Lock代码详解

    刚看到这个题目的时候无从下手,因为觉得synchronized和lock在加锁的方式上有很大不同,比如,看看正常情况下synchronized时如何加锁的. 方式一: public synchronized void a(){ //TODO } 方式二: public void b(){ synchronized(this){ //TODO } } 从这两种方式来看,锁都是加在{}之间的,我们再来看看Lock是如何做的呢: public void c() { lock.lock(); try {

  • 用c语言编写一个通讯录代码详解

    目录 实现通讯录的思路如下: 总结 实现通讯录的思路如下: 1.程序运行起来时用户首先要看到菜单栏选项并且对应菜单栏所给出的选项做出选择,这里我们简单设计一个Menu()函数可以让用户看见可选项目: 2.用户可选的范围应该是1~7,为了避免用户做出超出范围的选择我们可以用switch语句来判断用户的选择若用户输入的数字非法还可以让用户继续选择,而继续选择这个动作需要用到while语句,用户对通讯录的不断操作也需要用到while语句: 3.用户选择不同的选项,程序就要调用对应的函数来实现其功能并且

  • 一个通用的Java分页基类代码详解

    分页的基类 import java.util.List; /** * 分页显示的标准类,基本操作,是先给予-当前页数一共的数据条数-每页显示的条数, * 然后在初始化该类,得到总共页数,和开始序号和结束序号, * 然后数据库分页用到开始序号和结束序号,得到数据集合后赋值给该类的list属性, * * 然后把该类发送到jsp页面,进行访问 * @author admin * * @param <T> */ public class PageBean<T> { private int

  • 在Ubuntu上搭建一个基于webrtc的多人视频聊天服务实例代码详解

    WebRTC,即Web Real-Time Communication,web实时通信技术.简单地说就是在web浏览器里面引入实时通信,包括音视频通话等. 在疫情期间哪里也去不了,在家没事就研究webrtc视频直播技术,网上找了些教程最终都不太能顺利跑起来的,可能是文章写的比较老,使用的一些开源组件已经更新了,有些配置已经不太一样了,所以按照以前的步骤会有问题.折腾了一阵终于跑起来了,记录一下. 一个简单的聊天室html页面 这个页面使用simple-webrtc来实现webrtc的通讯,sim

  • 推荐一个好看Table表格的css样式代码详解

    漂亮的table表格样式css源码漂亮的table表格样式 源码 <head> <title></title> <style type="text/css"> table { border-collapse: collapse; margin: 0 auto; text-align: center; } table td, table th { border: 1px solid #cad9ea; color: #666; height:

  • Java多线程之线程通信生产者消费者模式及等待唤醒机制代码详解

    前言 前面的例子都是多个线程在做相同的操作,比如4个线程都对共享数据做tickets–操作.大多情况下,程序中需要不同的线程做不同的事,比如一个线程对共享变量做tickets++操作,另一个线程对共享变量做tickets–操作,这就是大名鼎鼎的生产者和消费者模式. 正文 一,生产者-消费者模式也是多线程 生产者和消费者模式也是多线程的范例.所以其编程需要遵循多线程的规矩. 首先,既然是多线程,就必然要使用同步.上回说到,synchronized关键字在修饰函数的时候,使用的是"this"

  • Java编程实现排他锁代码详解

    一 .前言 某年某月某天,同事说需要一个文件排他锁功能,需求如下: (1)写操作是排他属性 (2)适用于同一进程的多线程/也适用于多进程的排他操作 (3)容错性:获得锁的进程若Crash,不影响到后续进程的正常获取锁 二 .解决方案 1. 最初的构想 在Java领域,同进程的多线程排他实现还是较简易的.比如使用线程同步变量标示是否已锁状态便可.但不同进程的排他实现就比较繁琐.使用已有API,自然想到 java.nio.channels.FileLock:如下 /** * @param file

  • java synchronized的用法及原理详解

    目录 为什么要用synchronized 使用方式 字节码语义 对象锁(monitor) 锁升级过程 为什么要用synchronized 相信大家对于这个问题一定都有自己的答案,这里我还是要啰嗦一下,我们来看下面这段车站售票的代码: /** * 车站开两个窗口同时售票 */ public class TicketDemo { public static void main(String[] args) { TrainStation station = new TrainStation(); //

  • Java synchronized与CAS使用方式详解

    目录 引言 synchronized synchronized的三种使用方式 synchronized的底层原理 JDK1.6对synchronized的优化 synchronized的等待唤醒机制 CAS 引言 上一篇文章中我们说过,volatile通过lock指令保证了可见性.有序性以及“部分”原子性.但在大部分并发问题中,都需要保证操作的原子性,volatile并不具有该功能,这时就需要通过其他手段来达到线程安全的目的,在Java编程中,我们可以通过锁.synchronized关键字,以及

  • CI框架(ajax分页,全选,反选,不选,批量删除)完整代码详解

    CodeIgniter 是一个小巧但功能强大的 PHP 框架,作为一个简单而"优雅"的工具包,它可以为开发者们建立功能完善的 Web 应用程序.是比较主流的一个PHP框架. 下面给大家介绍CI框架(ajax分页,全选,反选,不选,批量删除)完整代码,具体代码如下所示: //ajax分页+搜索(视图层) function ajax_page(page){ var sou = $('#sou').val(); $.ajax({ type: "POST", dataTyp

随机推荐