zoukankan      html  css  js  c++  java
  • Synchronized的应用

    对线程加锁用的synchronized关键字,这个关键字的用法主要也分为两种:

    一种是加在方法名之前,形如:synchronized methodeName(params){……};

    二是声明同步块,形如:synchronized(this){……};

    很明显,加在方法名之前的范围比较大,而声明同步块范围要小点,一般同步的范围越大,性能就越差,一般需要加锁进行同步的时候,肯定是范围越小越好,这样性能更好*。

    一、当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。 
    二、然而,当一个线程访问object的一个synchronized(this)同步代码块时,另一个线程仍然可以访问该object中的非synchronized(this)同步代码块。 
    三、尤其关键的是,当一个线程访问object的一个synchronized(this)同步代码块时,其他线程对object中所有其它synchronized(this)同步代码块的访问将被阻塞。

    class Singleton {
    	// 私有的构造函数,保证外类不能实例化本类
    	private Singleton() {
    	}
     
    	// 自己创建一个类的实例化
    	private static Singleton singleton;
     
    	// 创建一个get方法,返回一个实例s
    	public static Singleton getInstance(){
    		//判断singleton是否为null,如果为null,即判定需要实例化
    		if (singleton == null) {
    			singleton = new Singleton();
    		}
    		return singleton;
    	}
    }
    //单例模式懒汉模式,不加锁
    

      

    // 单例模式 - 懒汉式加锁-双重检查锁
    class Singleton {
    	private Singleton() {
    	}
     
    	private static Singleton singleton;
     
    	private static Singleton getInstance() {
    		if ( singleton == null) {
    			synchronized (Singleton.class) {
    				if ( singleton == null) {
    					 singleton = new Singleton();
    				}
    			}
    		}
    		return  singleton;
    	}
    }
    

      

  • 相关阅读:
    操作系统六文件管理
    Educational Codeforces Round 38 (Rated for Div. 2) ABCD
    51nod 1100 斜率最大
    51nod 最小方差
    51nod 1065 最小正子段和
    P1280 尼克的任务
    牛客小白月赛2
    Codeforces Round #210 (Div. 1) B 二分+dp
    江西财经大学第一届程序设计竞赛
    51nod 1596 搬货物
  • 原文地址:https://www.cnblogs.com/clc1996/p/12446907.html
Copyright © 2011-2022 走看看