• Lock和Synchronized的比较


    Lock接口

    Lock接口可以实现和Synchronized相同的功能, 但是Lock可以实例化为一个对象, 更加体现面向对象的思想, 基本使用方法如下:

         Lock l = ...;
         l.lock();
         try {
             // access the resource protected by this lock
         } finally {
             l.unlock();
         }

    示例代码:

     1 public class Test {
     2 
     3     public static void main(String[] args) {
     4         new Test().init();
     5     }
     6     
     7     private void init(){
     8         Outputer outputer = new Outputer();
     9         //新建第一个线程
    10         new Thread(new Runnable(){
    11             public void run() {
    12                 while(true){
    13                     try {
    14                         Thread.sleep(10);
    15                     } catch (InterruptedException e) {
    16                         e.printStackTrace();
    17                     }
    18                     outputer.output("shen_smile");
    19                 }
    20             }
    21         }).start();
    22         //新建第二个线程
    23         new Thread(new Runnable(){
    24             public void run() {
    25                 while(true){
    26                     try {
    27                         Thread.sleep(10);
    28                     } catch (InterruptedException e) {
    29                         e.printStackTrace();
    30                     }
    31                     outputer.output("LockTest");
    32                 }
    33             }
    34         }).start();
    35     }
    36     //静态内部类
    37     static class Outputer{
    38         Lock lock = new ReentrantLock();//新建一个锁对象
    39         public void output(String name){
    40             int len = name.length();
    41             lock.lock();
    42             try{
    43                 for(int i=0;i<len;i++){
    44                     System.out.print(name.charAt(i));
    45                 }
    46                 System.out.println();
    47             }finally{
    48                 lock.unlock();
    49             }
    50         }
    51         //用synchronized实现代码段的互斥调用
    52         public synchronized void output2(String name){
    53             int len = name.length();
    54             for(int i=0;i<len;i++){
    55                 System.out.print(name.charAt(i));
    56             }
    57             System.out.println();
    58         }
    59     }
    60 }

    总结:

    1. 当两个线程都使用同一个Outputer类的对象的同一个output方法时, 各个线程之间就能实现互斥调用

    2. Lock和 Synchronized具有相同的功能, 但是 Lock比 Synchronized更加体现面向对象的思想, 因为锁本身就是一个对象

  • 相关阅读:
    在intellij 下用java spring + Mysql + Hibernate 开发的第一个数据库demo
    推荐一个找到一个比较好的spring,java学习教程
    ReactiveCocoa 中signal(operation) then与doNext的区别
    grunt
    Swiper.js wap app 图片滑动效果
    less 路径 写法
    html5 input placeholder 占位符 输入框提示文本
    js 大小写转换
    css 修改选中文字的颜色
    keydown keypress keyup textInput
  • 原文地址:https://www.cnblogs.com/shen-smile/p/5137892.html
Copyright © 2020-2023  润新知