Java面试常问技术点回顾

Java多线程实现的四种方式

  1. 继承Thread类创建线程
  2. 实现Runnable接口创建线程
  3. 实现Callable接口通过FutureTask包装器来创建Thread线程
  4. 使用ExecutorService、Callable、Future实现有返回结果的线程
    ExecutorService、Callable、Future三个接口实际上都是属于Executor框架。返回结果的线程是在JDK1.5中引入的新特征,有了这种特征就不需要再为了得到返回值而大费周折了。而且自己实现了也可能漏洞百出。

手写单例模式
饿汉式:
写法简单,但是无法做到延迟创建对象。但是我们很多时候都希望对象可以尽可能地延迟加载,从而减小负载,所以就需使用懒汉法。。。

public class Singleton{
	private static Singleton = new Singleton();
	pricate Singleton(){
		return singleton;
	}
}

懒汉式:

public class Singleton{
	private static Singleton singleton = null;
	private static Singleton getSingleton(){
		if(singleton == null){
		singleton = new Singleton
	}
	return singleton;
	}
}

究极进化版:
既有效率又安全

public class Singleton {
    private static volatile Singleton singleton = null;
    
    private Singleton(){}
    
    public static Singleton getSingleton(){
        if(singleton == null){
            synchronized (Singleton.class){
                if(singleton == null){
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }    
}

Why can’t traits call constants by class name???

猜你喜欢

转载自blog.csdn.net/qq_41212491/article/details/88976405