搜索
首页后端开发php教程使用synchronized实现一个Lock代码详解

本文给大家介绍了如何使用synchronized实现一个Lock代码,下面是实战案例,需要的朋友可以参考借鉴一下。

方式一:

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


相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

相关阅读:

php如何实现栈数据结构以及括号匹配算法的代码示例详解

php中最简单的字符串匹配算法,php匹配算法_PHP教程

最简单的php中字符串匹配算法教程

以上是使用synchronized实现一个Lock代码详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Java多线程中Lock怎么使用Java多线程中Lock怎么使用May 12, 2023 pm 02:46 PM

Jdk1.5以后,在java.util.concurrent.locks包下,有一组实现线程同步的接口和类,说到线程的同步,可能大家都会想到synchronized关键字,这是java内置的关键字,用来处理线程同步的,但这个关键字有很多的缺陷,使用起来也不是很方便和直观,所以就出现了Lock,下面,我们就来对比着讲解Lock。通常我们在使用synchronized关键字的时候会遇到下面这些问题:(1)不可控性,无法做到随心的加锁和释放锁。(2)效率比较低下,比如我们现在并发的读两个文件,读与读之

Java中Synchronized的原理和使用场景以及Callable接口的使用方法及区别分析Java中Synchronized的原理和使用场景以及Callable接口的使用方法及区别分析Apr 21, 2023 am 08:04 AM

一、基本特点1.开始时是乐观锁,如果锁冲突频繁,就转换为悲观锁.2.开始是轻量级锁实现,如果锁被持有的时间较长,就转换成重量级锁.3.实现轻量级锁的时候大概率用到的自旋锁策略4.是一种不公平锁5.是一种可重入锁6.不是读写锁二、加锁工作过程JVM将synchronized锁分为无锁、偏向锁、轻量级锁、重量级锁状态。会根据情况,进行依次升级。偏向锁假设男主是一个锁,女主是一个线程.如果只有这一个线程来使用这个锁,那么男主女主即使不领证结婚(避免了高成本操作),也可以一直幸福的生活下去.但是女配出现

Java中Lock的使用方式有哪些?Java中Lock的使用方式有哪些?Apr 23, 2023 pm 08:52 PM

1.作用(1)Lock方式来获取锁支持中断、超时不获取、是非阻塞的(2)提高了语义化,哪里加锁,哪里解锁都得写出来(3)Lock显式锁可以给我们带来很好的灵活性,但同时我们必须手动释放锁(4)支持Condition条件对象(5)允许多个读线程同时访问共享资源2.lock用法//获取锁voidlock()//如果当前线程未被中断,则获取锁voidlockInterruptibly()//返回绑定到此Lock实例的新Condition实例ConditionnewCondition()//仅在调用时锁

Java Lock类提供哪些功能?Java Lock类提供哪些功能?Apr 21, 2023 am 08:16 AM

说明1、Lock是java.util.concurent包下的接口,定义了一系列的锁定操作方法。2、Lock界面主要包括ReentrantLock、ReentrantReadWriteLock、ReentrantReadWriteLock、WriteLock实现类。与Synchronized不同,Lock提供了获取锁、释放锁等相关界面,使其使用更加灵活,操作更加复杂。实例ReentrantReadWriteLocklock=newReentrantReadWriteLock();Lockread

Java关键字synchronized原理与锁的状态实例分析Java关键字synchronized原理与锁的状态实例分析May 11, 2023 pm 03:25 PM

一、Java中锁的概念自旋锁:是指当一个线程获取锁的时候,如果锁已经被其它线程获取,那么该线程将循环等待,然后不断的判断锁是否能被成功获取,直到获取到锁才会退出循环。乐观锁:假定没有冲突,在修改数据时如果发现数据和之前获取的不一致,则读最新数据,重试修改。悲观锁:假定会发生并发冲突,同步所有对数据的相关操作,从读数据就开始上锁。独享锁(写):给资源加上写锁,线程可以修改资源,其它线程不能再加锁(单写)。共享锁(读):给资源加上读锁后只能读不能修改,其它线程也只能加读锁,不能加写锁(多度)。看成S

Java中如何利用synchronized实现同步机制?Java中如何利用synchronized实现同步机制?Apr 22, 2023 pm 02:46 PM

Java的synchronized使用方法总结1.把synchronized当作函数修饰符时,示例代码如下:Publicsynchronizedvoidmethod(){//….}这也就是同步方法,那这时synchronized锁定的是哪个对象呢?他锁定的是调用这个同步方法对象。也就是说,当一个对象P1在不同的线程中执行这个同步方法时,他们之间会形成互斥,达到同步的效果。但是这个对象所属的Class所产生的另一对象P2却能够任意调用这个被加了synchronized关键字的方法。上边的示例代码等

Java中的三种同步方式和它们的使用方法是什么?Java中的三种同步方式和它们的使用方法是什么?Apr 27, 2023 am 09:34 AM

1、说明synchronized算是我们最常用的同步方式,主要有三种使用方式。2、实例//普通类方法同步synchronizedpublidvoidinvoke(){}//类静态方法同步synchronizedpublicstaticvoidinvoke(){}//代码块同步synchronized(object){}这三种方式的不同之处在于同步的对象不同,普通类synchronized同步的是对象本身,静态方法同步的是类Class本身,代码块同步的是我们在括号内部填写的对象。Java有哪些集合

Java Synchronized锁升级原理及过程是什么Java Synchronized锁升级原理及过程是什么Apr 19, 2023 pm 10:22 PM

工具准备在正式谈synchronized的原理之前我们先谈一下自旋锁,因为在synchronized的优化当中自旋锁发挥了很大的作用。而需要了解自旋锁,我们首先需要了解什么是原子性。所谓原子性简单说来就是一个一个操作要么不做要么全做,全做的意思就是在操作的过程当中不能够被中断,比如说对变量data进行加一操作,有以下三个步骤:将data从内存加载到寄存器。将data这个值加一。将得到的结果写回内存。原子性就表示一个线程在进行加一操作的时候,不能够被其他线程中断,只有这个线程执行完这三个过程的时候

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
2 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具