我在java中编写了一些多线程代码,并且改变了变量的同步方法,但它没有同步我的代码,我仍然得到随机值.有我的代码:
public class Main {
public static void main(String[] args) throws Exception {
Resource.i = 5;
MyThread myThread = new MyThread();
myThread.setName("one");
MyThread myThread2 = new MyThread();
myThread.start();
myThread2.start();
myThread.join();
myThread2.join();
System.out.println(Resource.i);
}
}
class MyThread extends Thread {
@Override
public void run() {
synMethod();
}
private synchronized void synMethod() {
int i = Resource.i;
if(Thread.currentThread().getName().equals("one")) {
Thread.yield();
}
i++;
Resource.i = i;
}
}
class Resource {
static int i;
}
Run Code Online (Sandbox Code Playgroud)
有时我得7,有时6,但是我已经同步了synMethod,因为据我所知,没有线程应该使用这个方法,而其他一些线程执行这个,所以操作应该是原子的,但它们不是,我不明白为什么?你可以向我解释一下,并回答 - 我该如何解决?
我有 Spring Boot,我需要在数据库中记录用户操作,所以我编写了 HandlerInterceptor:
@Component
public class LogInterceptor implements HandlerInterceptor {
@Autovired
private LogUserActionService logUserActionService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws IOException {
String userName = SecurityContextHolder.getContext().getAuthentication().getName();
String url = request.getRequestURI();
String queryString = request.getQueryString() != null ? request.getQueryString() : "";
String body = "POST".equalsIgnoreCase(request.getMethod()) ? new BufferedReader(new InputStreamReader(request.getInputStream())).lines().collect(Collectors.joining(System.lineSeparator())) : queryString;
logUserActionService.logUserAction(userName, url, body);
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
但根据这个答案Get RequestBody and ResponseBody at HandlerInterceptor "RequestBody can be read only Once",所以据我了解,我读取输入流,然后 Spring 尝试执行相同的操作,但流已被读取,并且我收到错误: “缺少所需的请求正文......”
所以我尝试了不同的方法来制作缓冲输入流,即:
HttpServletRequest …Run Code Online (Sandbox Code Playgroud)