面试八股文之Java基础(四)----hashMap 线程不安全体现,如何让解决?创建对象的五种方式、多线程的创建方式有哪些?

hashMap线程不安全体现

在 「hashMap1.7 中扩容」的时候,因为采用的是头插法,所以会可能会有循环链表产生,导致数据有问题,在 1.8 版本已修复,改为了尾插法

在任意版本的 hashMap 中,如果在「插入数据时多个线程命中了同一个槽」,可能会有数据覆盖的情况发生,导致线程不安全。

怎么解决?

一.给 hashMap 「直接加锁」,来保证线程安全

二.使用 「hashTable」,比方法一效率高,其实就是在其方法上加了 synchronized 锁

三.使用 「concurrentHashMap」 , 不管是其 1.7 还是 1.8 版本,本质都是「减小了锁的粒度,减少线程竞争」来保证高效.

五种创建对象的方式

  • 1、new关键字
Person p1 = new Person();
  • 2.Class.newInstance
Person p1 = Person.class.newInstance();
  • 3.Constructor.newInstance
Constructor<Person> constructor = Person.class.getConstructor();
Person p1 = constructor.newInstance();
  • 4.clone
Person p1 = new Person();
Person p2 = p1.clone();
  • 5.反序列化
Person p1 = new Person();
byte[] bytes = SerializationUtils.serialize(p1);
Person p2 = (Person)SerializationUtils.deserialize(bytes);

多线程的创建方式有哪些?

  • 1、「继承Thread类」,重写run()方法
public class Demo extends Thread{
    //重写父类Thread的run()
    public void run() {
    }
    public static void main(String[] args) {
        Demo d1 = new Demo();
        Demo d2 = new Demo();
        d1.start();
        d2.start();
    }
}
  • 2.「实现Runnable接口」,重写run()
public class Demo2 implements Runnable{

    //重写Runnable接口的run()
    public void run() {
    }
    
    public static void main(String[] args) {
        Thread t1 = new Thread(new Demo2());
        Thread t2 = new Thread(new Demo2());
        t1.start();
        t2.start();
    }

}
  • 3.「实现 Callable 接口」
public class Demo implements Callable<String>{

    public String call() throws Exception {
        System.out.println("正在执行新建线程任务");
        Thread.sleep(2000);
        return "结果";
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Demo d = new Demo();
        FutureTask<String> task = new FutureTask<>(d);
        Thread t = new Thread(task);
        t.start();
        //获取任务执行后返回的结果
        String result = task.get();
    }
    
}
  • 4.「使用线程池创建」
public class Demo {
    public static void main(String[] args) {
        Executor threadPool = Executors.newFixedThreadPool(5);
        for(int i = 0 ;i < 10 ; i++) {
            threadPool.execute(new Runnable() {
                public void run() {
                    //todo
                }
            });
        }
        
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值