自学内容网 自学内容网

java数组在多线程中安全问题,HashMap是不安全的,Hashtable安全(但每次都加锁,效率低),ConcurrentHashMap完美

package com.controller;

import com.myThread.AdminThread;
import com.myThread.MyCallable;
import com.myThread.MyRunnable;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.*;
//上面引入*,所以这个可以注销
//import java.util.concurrent.ConcurrentHashMap;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController{
    @GetMapping("/{id}")
    public long findById(@PathVariable Long id) throws InterruptedException {
        ConcurrentHashMap<String,String> maps = new ConcurrentHashMap<>();
        Thread ti = new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                maps.put(i+"",i+"laila");
            }
        });
        ti.start();
        //加一下延迟,等线程把数据写入,不然是null
        Thread.sleep(1000);

        for (int i = 0; i < 10; i++) {
            System.out.print(maps.get(i+"")+"\n");
        }
        return id;
    }
}

在这里插入图片描述


原文地址:https://blog.csdn.net/qq_34631220/article/details/135707037

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!