【发布时间】:2021-06-19 15:03:26
【问题描述】:
使用 Spring Boot 时方法(不使用类变量)是否线程安全? 我遇到了他们提到实例变量并不总是安全的龋齿链接?
我的疑问是如何创建竞争条件?下面的代码是线程安全的吗?如果是,那么我怎样才能使它成为线程 - 不使用类变量的不安全
@RestController
public class GreetingController {
@Autowired
private GreetingService greetingService;
@GetMapping("/hello")
public void greeting(@RequestBody MyUser myUser) throws Exception {
greetingService.getData(myUser);
}
@Service
public class GreetingService {
@Autowired
private DBService dBService;
public void getData (MyUser m ) throws InterruptedException
{
dBService.getData(m);
}
@Repository
public class DBService {
public MyUser getData(MyUser myUser) throws InterruptedException {
System.out.println( "message before: " + myUser.getA() + " Thread : " +Thread.currentThread().getName());
Thread.sleep(18000);
System.out.println( "message after " + myUser.getA() + " Thread : " +Thread.currentThread().getName());
return myUser;
}
【问题讨论】:
标签: java spring multithreading spring-boot