栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java笔记整理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java笔记整理

Java技术点笔记,期待共同进步,持续更新中……

关键字 instanceof
  • 写法:object instanceof Object
  • 作用:判断对象object是不是类Object的实例,是则返回true,不是则返回false。object为null时,始终返回false。
  • 实例:判断任意对象是否是String类的实例
    public boolean isString(T t) {
        return t instanceof String;
    }
  • 应用场景:需要判断一个对象是不是预期的一个类的实例时,推荐该关键字,常用于工具、框架中,业务代码中较少使用。在对象实例强转类型前,使用该关键字较多,可以减少强转报错的出现。
  • 相似技术:Class类的isInstance()方法,官方文档如下,可自行翻译理解:

public boolean isInstance(Object obj)

  • Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.
  • Specifically, if this Class object represents a declared class, this method returns true if the specified Object argument is an instance of the represented class (or of any of its subclasses); it returns false otherwise. If this Class object represents an array class, this method returns true if the specified Object argument can be converted to an object of the array class by an identity conversion or by a widening reference conversion; it returns false otherwise. If this Class object represents an interface, this method returns true if the class or any superclass of the specified Object argument implements this interface; it returns false otherwise. If this Class object represents a primitive type, this method returns false.
synchronized
  • 写法:主要有三种:锁对象、锁方法、锁代码块
// 锁对象(this是当前对象)
synchronized (this) {
    // 逻辑代码
}

// 锁方法,此时该方法是个同步方法
public synchronized void synMethod() {
	// 方法体
}

// 锁代码块(object其他变量对象)
synchronized (object) {
    // 逻辑代码
}
  • 作用:同步锁关键字,使用该关键字后,该关键字生效范围内的代码,只能同时被一个线程执行,且是由JVM自动管理执行状态。
  • 实例:懒汉式单例模式:
public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
    public static synchronized Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  
}
  • 应用场景:部分业务场景中,多线程同时执行一个逻辑时,会导致业务出错,需要限制只能有一个线程在执行当前业务逻辑的情况下,可以使用synchronized关键字,如:电商销售场景、库存出库场景、银行支付场景等。
  • 相似技术:java.util.concurrent.locks.Lock接口,这种方式可以手动控制加锁解锁,有兴趣可自行搜索。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/825466.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号