浅谈多线程中的锁的几种用法总结(必看)

一、ReentrantLock

package com.ietree.basicskill.mutilthread.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Administrator on 2017/5/17.
 */
public class UseReentrantLock {

  private Lock lock = new ReentrantLock();

  public void method1(){
    try {
      lock.lock();
      System.out.println("当前线程:" + Thread.currentThread().getName() + "进入method1..");
      Thread.sleep(1000);
      System.out.println("当前线程:" + Thread.currentThread().getName() + "退出method1..");
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {

      lock.unlock();
    }
  }

  public void method2(){
    try {
      lock.lock();
      System.out.println("当前线程:" + Thread.currentThread().getName() + "进入method2..");
      Thread.sleep(2000);
      System.out.println("当前线程:" + Thread.currentThread().getName() + "退出method2..");
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {

      lock.unlock();
    }
  }

  public static void main(String[] args) {

    final UseReentrantLock ur = new UseReentrantLock();
    Thread t1 = new Thread(new Runnable() {
      @Override
      public void run() {
        ur.method1();
        ur.method2();
      }
    }, "t1");

    t1.start();
    try {
      Thread.sleep(10);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    //System.out.println(ur.lock.getQueueLength());
  }

}

二、ReentrantReadWriteLock

package com.ietree.basicskill.mutilthread.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by Administrator on 2017/5/17.
 */
public class UseReentrantReadWriteLock {

  private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
  private ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
  private ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();

  public void read(){
    try {
      readLock.lock();
      System.out.println("当前线程:" + Thread.currentThread().getName() + "进入...");
      Thread.sleep(3000);
      System.out.println("当前线程:" + Thread.currentThread().getName() + "退出...");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      readLock.unlock();
    }
  }

  public void write(){
    try {
      writeLock.lock();
      System.out.println("当前线程:" + Thread.currentThread().getName() + "进入...");
      Thread.sleep(3000);
      System.out.println("当前线程:" + Thread.currentThread().getName() + "退出...");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      writeLock.unlock();
    }
  }

  public static void main(String[] args) {

    final UseReentrantReadWriteLock urrw = new UseReentrantReadWriteLock();

    Thread t1 = new Thread(new Runnable() {
      @Override
      public void run() {
        urrw.read();
      }
    }, "t1");
    Thread t2 = new Thread(new Runnable() {
      @Override
      public void run() {
        urrw.read();
      }
    }, "t2");
    Thread t3 = new Thread(new Runnable() {
      @Override
      public void run() {
        urrw.write();
      }
    }, "t3");
    Thread t4 = new Thread(new Runnable() {
      @Override
      public void run() {
        urrw.write();
      }
    }, "t4");

//    t1.start();
//    t2.start();

//    t1.start(); // R
//    t3.start(); // W

    t3.start();
    t4.start();
  }
}

三、Condition

package com.ietree.basicskill.mutilthread.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Administrator on 2017/5/17.
 */
public class UseCondition {
  private Lock lock = new ReentrantLock();
  private Condition condition = lock.newCondition();

  public void method1(){
    try {
      lock.lock();
      System.out.println("当前线程:" + Thread.currentThread().getName() + "进入等待状态..");
      Thread.sleep(3000);
      System.out.println("当前线程:" + Thread.currentThread().getName() + "释放锁..");
      condition.await();  // Object wait
      System.out.println("当前线程:" + Thread.currentThread().getName() +"继续执行...");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void method2(){
    try {
      lock.lock();
      System.out.println("当前线程:" + Thread.currentThread().getName() + "进入..");
      Thread.sleep(3000);
      System.out.println("当前线程:" + Thread.currentThread().getName() + "发出唤醒..");
      condition.signal();    //Object notify
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public static void main(String[] args) {

    final UseCondition uc = new UseCondition();
    Thread t1 = new Thread(new Runnable() {
      @Override
      public void run() {
        uc.method1();
      }
    }, "t1");
    Thread t2 = new Thread(new Runnable() {
      @Override
      public void run() {
        uc.method2();
      }
    }, "t2");
    t1.start();

    t2.start();
  }
}

四、ManyCondition

package com.ietree.basicskill.mutilthread.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Administrator on 2017/5/17.
 */
public class UseManyCondition {
  private ReentrantLock lock = new ReentrantLock();
  private Condition c1 = lock.newCondition();
  private Condition c2 = lock.newCondition();

  public void m1(){
    try {
      lock.lock();
      System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m1等待..");
      c1.await();
      System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m1继续..");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void m2(){
    try {
      lock.lock();
      System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m2等待..");
      c1.await();
      System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m2继续..");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void m3(){
    try {
      lock.lock();
      System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m3等待..");
      c2.await();
      System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m3继续..");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void m4(){
    try {
      lock.lock();
      System.out.println("当前线程:" +Thread.currentThread().getName() + "唤醒..");
      c1.signalAll();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void m5(){
    try {
      lock.lock();
      System.out.println("当前线程:" +Thread.currentThread().getName() + "唤醒..");
      c2.signal();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public static void main(String[] args) {

    final UseManyCondition umc = new UseManyCondition();
    Thread t1 = new Thread(new Runnable() {
      @Override
      public void run() {
        umc.m1();
      }
    },"t1");
    Thread t2 = new Thread(new Runnable() {
      @Override
      public void run() {
        umc.m2();
      }
    },"t2");
    Thread t3 = new Thread(new Runnable() {
      @Override
      public void run() {
        umc.m3();
      }
    },"t3");
    Thread t4 = new Thread(new Runnable() {
      @Override
      public void run() {
        umc.m4();
      }
    },"t4");
    Thread t5 = new Thread(new Runnable() {
      @Override
      public void run() {
        umc.m5();
      }
    },"t5");

    t1.start();  // c1
    t2.start();  // c1
    t3.start();  // c2

    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    t4.start();  // c1
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    t5.start();  // c2

  }
}

以上这篇浅谈多线程中的锁的几种用法总结(必看)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 关于多线程常用方法以及对锁的控制(详解)

    1.sleep() 使当前线程(即调用该方法的线程)暂停执行一段时间,让其他线程有机会继续执行,但它并不释放对象锁.也就是如果有Synchronized同步块,其他线程仍然不同访问共享数据.注意该方法要捕获异常 比如有两个线程同时执行(没有Synchronized),一个线程优先级为MAX_PRIORITY,另一个为MIN_PRIORITY,如果没有Sleep()方法,只有高优先级的线程执行完成后,低优先级的线程才能执行:但当高优先级的线程sleep(5000)后,低优先级就有机会执行了. 总之

  • 浅谈多线程中的锁的几种用法总结(必看)

    一.ReentrantLock package com.ietree.basicskill.mutilthread.lock; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by Administrator on 2017/5/17. */ public class UseReentrantLock { private Lock lock

  • 浅谈python中统计计数的几种方法和Counter详解

    1) 使用字典dict() 循环遍历出一个可迭代对象中的元素,如果字典没有该元素,那么就让该元素作为字典的键,并将该键赋值为1,如果存在就将该元素对应的值加1. lists = ['a','a','b',5,6,7,5] count_dict = dict() for item in lists: if item in count_dict: count_dict[item] += 1 else: count_dict[item] = 1 2) 使用defaultdict() defaultdi

  • 浅谈keras中的目标函数和优化函数MSE用法

    mean_squared_error / mse 均方误差,常用的目标函数,公式为((y_pred-y_true)**2).mean() model = Sequential() model.add(Dense(64, init='uniform', input_dim=10)) model.add(Activation('tanh')) model.add(Activation('softmax')) sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, ne

  • 浅谈js中的attributes和Attribute的用法与区别

    一:Attribute的几种用法和含义(attributes和Attribute都是用来操作属性的) getAttribute:获取某一个属性的值: setAttribute:建立一个属性,并同时给属性捆绑一个值: createAttribute:仅建立一个属性: removeAttribute:删除一个属性: getAttributeNode:获取一个节点作为对象: setAttributeNode:建立一个节点: removeAttributeNode:删除一个节点: 1.getAttrib

  • 浅谈MYSQL中树形结构表3种设计优劣分析与分享

    目录 简介 问题 设计1:邻接表 表设计 SQL示例 设计2:路径枚举 表设计 SQL示例 设计3:闭包表 表设计 SQL示例 结合使用 表设计 总结 简介 在开发中经常遇到树形结构的场景,本文将以部门表为例对比几种设计的优缺点: 问题 需求背景:根据部门检索人员, 问题:选择一个顶级部门情况下,跨级展示当前部门以及子部门下的所有人员,表怎么设计更合理 ? 递归吗 ?递归可以解决,但是势必消耗性能 设计1:邻接表 注:(常见父Id设计) 表设计 CREATE TABLE `dept_info01

  • 浅谈PHP的exec()函数无返回值排查方法(必看)

    在安全imagemagic时 需要用到 exec很多服务器上安装失败 exec()执行外部命令失败,但没有任何错误信息. exec执行某命令在命令行下没有问题,但是在php中就出错.这个问题99.99%与权限有关,但是exec执行的命令不会返回错误.一个技巧就是使用管道命令,假设你的exec调用如下: exec('convert a.jpg b.jpg', $output, $return_val); 可以更改如下: exec('convert a.jpg b.jpg 2>&1', $out

  • 浅谈django model的get和filter方法的区别(必看篇)

    django的get和filter方法是django model常用到的,搞清楚两者的区别非常重要. 为了说明它们两者的区别定义2个models class Student(models.Model): name = models.CharField('姓名', max_length=20, default='') age = models.CharField('年龄', max_length=20, default='') class Book(models.Model): student =

  • SQL中实现SPLIT函数几种方法总结(必看篇)

    例1 代码如下 create function f_split(@SourceSql varchar(8000),@StrSeprate varchar(10)) returns @temp table(a varchar(100)) --实现split功能 的函数 --date :2003-10-14 as begin declare @i int set @SourceSql=rtrim(ltrim(@SourceSql)) set @i=charindex(@StrSeprate,@Sou

  • 浅谈iOS中的锁的介绍及使用

    在平时的开发中经常使用到多线程,在使用多线程的过程中,难免会遇到资源竞争的问题,那我们怎么来避免出现这种问题那? 线程安全是什么? 当一个线程访问数据的时候,其他的线程不能对其进行访问,直到该线程访问完毕.简单来讲就是在同一时刻,对同一个数据操作的线程只有一个.只有确保了这样,才能使数据不会被其他线程影响.而线程不安全,则是在同一时刻可以有多个线程对该数据进行访问,从而得不到预期的结果. 比如写文件和读文件,当一个线程在写文件的时候,理论上来说,如果这个时候另一个线程来直接读取的话,那么得到的结

  • 浅谈Java中实现深拷贝的两种方式—clone() & Serialized

    clone() 方法麻烦一些,需要将所有涉及到的类实现声明式接口 Cloneable,并覆盖Object类中的clone()方法,并设置作用域为public(这是为了其他类可以使用到该clone方法). 序列化的方法简单,需要将所有涉及到的类实现接口Serializable package b1ch06.clone; import java.io.Serializable; class Car implements Cloneable, Serializable { private String

随机推荐