1. 所需工具
- 集成开发工具(我的是STS)
- Tomcat,用来模拟真实请求响应服务(我的是Spring Boot内置有Tomcat)
2. 代码
- ThreadInsecurity类,主要用来提供服务,这里的服务也很简单。全局变量的累加,每请求一次就加3000;100以内的每次增加都会休眠100ms(为什么要休眠?为了模拟耗时的写入操作,以达到线程不安全现象。这是符合现实情况的)。
package thread;
import java.util.ArrayList;
import java.util.List;
public class ThreadInsecurity {
private static List<byte[]> byteList = new ArrayList<>();
public static void clear() {
if (!byteList.isEmpty()) {
System.out.println("开始清除byteList数据");
byteList.clear();
}
}
public static List<byte[]> getByteList() {
return byteList;
}
public static String addByte() {
int count = 0;
while (count < 3000) {
if (count < 100) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
byteList.add(new byte[4096 * 10]);
count++;
}
String value = "Thread=" + Thread.currentThread().getName() + ", byteList's HashCode=" + byteList.hashCode() + ", size=" + byteList.size();
System.out.println(value);
return value;
}
}
- controller,提供服务,url是http://localhost:1010/sprintboot/thread_insecurity。
package com.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import thread.ThreadInsecurity;
@RestController
public class ThreadController {
@RequestMapping("/thread_insecurity")
public String threadInsecurity() {
System.out.println("The front-end request is received and the thread, " + Thread.currentThread().getName() + " is started!");
String value = ThreadInsecurity.addByte();
return value;
}
}
3. 测试与分析
我是用浏览器快速连续发起6次请求(如何做到呢?先打开窗口把url复制进去,不要回车,连续打开复制6个,这样子做完,再快速的回车—切换窗口—回车),几乎可以说是同时发起请求。
看看前端连续发起6次请求图片:
看看STS里的Console:
需要说明一下,我发起这连续的6次请求之前是有发起过4次请求的,即从size=12000(3000*4)开始。
从图片可以知道:Tomcat是使用线程池的,里面有10个nio线程(这个可以使用JConsole验证);看最后那4次size不是整数了。说明线程不安全,简单解释就是全局变量是存放在方法区的,这是线程共享的。多线程做写入操作就会有线程不安全问题。
4. 结论
在类中有静态全局变量,且这个变量存在写入操作时就要考虑线程安全问题了。下次我们看看如何解决这个非线程安全问题。