大厂面试题:
1、请你谈谈对volatile的理解?
2、CAS你知道吗?
3、原子类AtomicInteger的ABA问题谈谈?原子更新引用知道吗?
4、我们都知道ArrayList是线程不安全的,请编码写一个不安全的案例并给出解决方案?
5、公平锁/非公平锁/可重入锁/递归锁/自旋锁谈谈你的理解?请手写一个自旋锁。
6、CountDownLatch、CyclicBarrier、Semaphore使用过吗?
7、阻塞队列知道吗?
8、线程池用过吗?ThreadPoolExecutor谈谈你的理解?
9、线程池用过吗?生产上你是如何设置合理参数?
10、死锁编码及定位分析?
public class SingletonDemo {
private static SingletonDemo singletonDemo = null;
private SingletonDemo() {
System.out.println(Thread.currentThread().getName() + "\t" + "SingletonDemo构造方法创建");
}
public static SingletonDemo getInstance() {
if (singletonDemo == null) {
singletonDemo = new SingletonDemo();
}
return singletonDemo;
}
public static void main(String[] args) {
// 单线程main情况下,单例模式下只会创建一次SingletonDemo对象
System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
}
}
程序执行结果如下:
public class SingletonDemo {
private static SingletonDemo singletonDemo = null;
private SingletonDemo() {
System.out.println(Thread.currentThread().getName() + "\t" + "SingletonDemo构造方法创建");
}
public static SingletonDemo getInstance() {
if (singletonDemo == null) {
singletonDemo = new SingletonDemo();
}
return singletonDemo;
}
public static void main(String[] args) {
// 多线程情况下,单例模式存在线程不安全,会创建多次SingletonDemo对象
for (int i = 0; i < 10; i++) {
new Thread(() -> {
SingletonDemo.getInstance();
}, String.valueOf(i)).start();
}
}
}
程序执行结果如下:
public class SingletonDemo {
private static SingletonDemo singletonDemo = null;
private SingletonDemo() {
System.out.println(Thread.currentThread().getName() + "\t" + "SingletonDemo构造方法创建");
}
public static synchronized SingletonDemo getInstance() {
if (singletonDemo == null) {
singletonDemo = new SingletonDemo();
}
return singletonDemo;
}
public static void main(String[] args) {
// 多线程情况下,单例模式存在线程不安全,会创建多次SingletonDemo对象
for (int i = 0; i < 10; i++) {
new Thread(() -> {
SingletonDemo.getInstance();
}, String.valueOf(i)).start();
}
}
}
程序执行结果如下:
volatile使用场景请接着看下一篇博客
参考答案请看下一小节:单例模式volatile分析