Java | 面试题(1)

面试题1:自增变量

如下代码的运行结果:

/**
 * ClassName: Test1
 * Date:      2020/2/25 22:29
 * author:    Oh_MyBug
 * version:   V1.0
 */
public class Test1 {
    public static void main(String[] args) {
        int i = 1;
        i = i ++;
        int j = i ++;
        int k = i + ++i * i++;
        System.out.println("i = " + i);
        System.out.println("j = " + j);
        System.out.println("k = " + k);
    }
}
// 输出:
i = 4
j = 1
k = 11

总结

  • 赋值=,最后计算
  • =右边的从左到右加载值依次压入操作数栈
  • 实际先算哪个,看运算符优先级
  • 自增、自减操作都是直接修改变量的值,不经过操作数栈
  • 最后的赋值之前,临时结果也是存储在操作数栈中

面试题2:单例设计模式

编程题:写一个singleton示例

什么是Singleton?

  • Singleton:在Java中指单例设计模式,它是软件开发中最常用的设计模式之一。
  • 单:一个
  • 例:实例
  • 单例设计模式,即某个类在整个系统中只能有一个实例对象可被获取和使用的代码模式。
  • 例如:代表JVM运行环境的Runtime类

要点

  • 某个类只能有一个实例
    • 构造器私有化
  • 它必须自行创建这个实例
    • 含有一个该类的静态变量来保存这个唯一的实例
  • 它必须自行向整个系统提供这个实例
    • 对外提供获取该实例对象的方式:
      • 直接暴露
      • 用静态变量的get方法获取

几种常见形式

  • 饿汉式:直接创建对象,不存在线程安全问题
    • 直接实例化饿汉式(简洁直观)
    • 枚举式(最简洁)
    • 静态代码块饿汉式(适合复杂实例化)
/**
 * ClassName: Singleton1
 * Date:      2020/2/25 23:30
 * author:    Oh_MyBug
 * version:   V1.0
 *  饿汉式:
 *   在类初始化的时候直接创建实例对象,不管你是否需要这个对象
 *
 * (1)构造器私有化
 * (2)自行创建,并且用静态变量保存
 * (3)向外提供这个实例
 * (4)强调这是一个单例,我们可以用final修饰
 */
public class Singleton1 {
    public static final Singleton1 INSTANCE = new Singleton1();
    private Singleton1(){

    }
}
/**
 * ClassName: TestSingleton1
 * Date:      2020/2/25 23:36
 * author:    Oh_MyBug
 * version:   V1.0
 */
public class TestSingleton1 {
    public static void main(String[] args) {
        Singleton1 s = Singleton1.INSTANCE;
        System.out.println(s);
    }
}
// 输出:
Singleton1@10f87f48
/**
 * ClassName: Singleton2
 * Date:      2020/2/25 23:35
 * author:    Oh_MyBug
 * version:   V1.0
 * 枚举类型,表示该类型的对象是有限的几个
 * 我们可以限定为一个,就成了单例
 */
public enum  Singleton2 {
    INSTANCE
}
/**
 * ClassName: TestSingleton2
 * Date:      2020/2/25 23:37
 * author:    Oh_MyBug
 * version:   V1.0
 */
public class TestSingleton2 {
    public static void main(String[] args) {
        Singleton2 s = Singleton2.INSTANCE;
        System.out.println(s);
    }
}

//输出:
INSTANCE
import java.io.IOException;
import java.util.Properties;

/**
 * ClassName: Singleton3
 * Date:      2020/2/25 23:39
 * author:    Oh_MyBug
 * version:   V1.0
 */
public class Singleton3 {
    public static final Singleton3 INSTANCE;
    private String info;

    static {
        try {
            Properties pro = new Properties();

            pro.load(Singleton3.class.getClassLoader().getResourceAsStream("single.properties"));

            INSTANCE = new Singleton3(pro.getProperty("info"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private Singleton3(String info){
        this.info = info;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    @Override
    public String toString() {
        return "Singleton3{" +
                "info='" + info + '\'' +
                '}';
    }
}
/**
 * ClassName: TestSingle3
 * Date:      2020/2/25 23:48
 * author:    Oh_MyBug
 * version:   V1.0
 */
public class TestSingleton3 {
    public static void main(String[] args) {
        Singleton3 s = Singleton3.INSTANCE;
        System.out.println(s);
    }
}

// 输出:
Singleton3{info='Oh_MyBug'}
  • 懒汉式:延迟创建对象
    • 线程不安全(适用于单线程)
    • 线程安全(适用于多线程)
    • 静态内部类形式(适用于多线程)
/**
 * ClassName: SIngleton4
 * Date:      2020/2/25 23:54
 * author:    Oh_MyBug
 * version:   V1.0
 * 懒汉式:
 *  延迟创建这个实例对象
 * (1)构造器私有化
 * (2)用一个静态变量保存这个唯一的实例
 * (3)提供一个静态方法,获取这个实例对象
 */
public class Singleton4 {
    static Singleton4 instance;
    private Singleton4(){

    }
    public static Singleton4 getInstance(){
        if (instance == null){
            instance = new Singleton4();
        }
        return instance;
    }
}
/**
 * ClassName: TestSingleton4
 * Date:      2020/2/25 23:57
 * author:    Oh_MyBug
 * version:   V1.0
 */
public class TestSingleton4 {
    public static void main(String[] args) {
        Singleton4 s1 = Singleton4.getInstance();
        Singleton4 s2 = Singleton4.getInstance();

        System.out.println(s1 == s2);
        System.out.println(s1);
        System.out.println(s2);
    }
}
// 输出:
true
Singleton4@5b480cf9
Singleton4@5b480cf9

可能存在线程安全问题!

/**
 * ClassName: Singleton4
 * Date:      2020/2/25 23:54
 * author:    Oh_MyBug
 * version:   V1.0
 * 懒汉式:
 *  延迟创建这个实例对象
 * (1)构造器私有化
 * (2)用一个静态变量保存这个唯一的实例
 * (3)提供一个静态方法,获取这个实例对象
 */
public class Singleton4 {
    static Singleton4 instance;
    private Singleton4(){

    }
    public static Singleton4 getInstance(){
        if (instance == null){

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            instance = new Singleton4();
        }
        return instance;
    }
}
import java.util.concurrent.*;

/**
 * ClassName: TestSingleton4
 * Date:      2020/2/25 23:57
 * author:    Oh_MyBug
 * version:   V1.0
 */
public class TestSingleton4 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        Singleton4 s1 = Singleton4.getInstance();
//        Singleton4 s2 = Singleton4.getInstance();
//
//        System.out.println(s1 == s2);
//        System.out.println(s1);
//        System.out.println(s2);

        Callable<Singleton4> c = new Callable<Singleton4>() {
            @Override
            public Singleton4 call() throws Exception {
                return Singleton4.getInstance();
            }
        };

        ExecutorService es = Executors.newFixedThreadPool(2);
        Future<Singleton4> f1 = es.submit(c);
        Future<Singleton4> f2 = es.submit(c);

        Singleton4 s1 = f1.get();
        Singleton4 s2 = f2.get();

        System.out.println(s1 == s2);
        System.out.println(s1);
        System.out.println(s2);

        es.shutdown();
    }
}

// 输出:
false
Singleton4@1ddc4ec2
Singleton4@133314b
/**
 * ClassName: Singleton4
 * Date:      2020/2/25 23:54
 * author:    Oh_MyBug
 * version:   V1.0
 * 懒汉式:
 *  延迟创建这个实例对象
 * (1)构造器私有化
 * (2)用一个静态变量保存这个唯一的实例
 * (3)提供一个静态方法,获取这个实例对象
 */
public class Singleton5 {
    static Singleton5 instance;
    private Singleton5(){

    }
    public static Singleton5 getInstance(){
        if (instance == null) {
            synchronized (Singleton5.class) {
                if (instance == null) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    instance = new Singleton5();
                }
            }
        }
        return instance;
    }
}
import java.util.concurrent.*;

/**
 * ClassName: TestSingleton4
 * Date:      2020/2/25 23:57
 * author:    Oh_MyBug
 * version:   V1.0
 */
public class TestSingleton5 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<Singleton5> c = new Callable<Singleton5>() {
            @Override
            public Singleton5 call() throws Exception {
                return Singleton5.getInstance();
            }
        };

        ExecutorService es = Executors.newFixedThreadPool(2);
        Future<Singleton5> f1 = es.submit(c);
        Future<Singleton5> f2 = es.submit(c);

        Singleton5 s1 = f1.get();
        Singleton5 s2 = f2.get();

        System.out.println(s1 == s2);
        System.out.println(s1);
        System.out.println(s2);

        es.shutdown();
    }
}
// 输出:
true
Singleton5@1ddc4ec2
Singleton5@1ddc4ec2
/**
 * ClassName: Singleton6
 * Date:      2020/2/26 0:08
 * author:    Oh_MyBug
 * version:   V1.0
 * 在内部类被加载和初始化时,才创建INSTANCE实例对象
 * 静态内部类不会自动随着外部类的加载和初始化而初始化,它是要单独去加载和初始化
 * 因为是在内部类加载和初始化时创建的,因此是线程安全的
 */
public class Singleton6 {
    private Singleton6(){

    }

    private static class Inner{
        private static final Singleton6 INSTANCE = new Singleton6();
    }

    public static Singleton6 getInstance(){
        return Inner.INSTANCE;
    }
}
发布了36 篇原创文章 · 获赞 3 · 访问量 6223

猜你喜欢

转载自blog.csdn.net/Oh_MyBug/article/details/104508699
今日推荐