Java笔记整理

Java笔记整理,第1张

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

关键字 instanceof
  • 写法:object instanceof Object
  • 作用:判断对象object是不是类Object的实例,是则返回true,不是则返回falseobjectnull时,始终返回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接口,这种方式可以手动控制加锁解锁,有兴趣可自行搜索。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/725820.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存