1.答案
- 1.如果在类中声明成员变量,并且有读写操作(有状态),就会线程不安全。否则线程安全。
2.不安全代码示例
package com.learning.beanthreadsafe;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author wangyouhui
* @Description 单例是否线程安全
**/
@Configuration
public class MainConfig {
@Bean
public UserService userService(){
return new UserService();
}
}
package com.learning.beanthreadsafe;
/**
* @Author wangyouhui
* @Description 单例是否线程安全
**/
public class UserService {
private String username;
public String welcome(String username){
this.username = "welcome:" + username;
// 处理业务
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return this.username;
}
}
package com.learning.beanthreadsafe;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @Author wangyouhui
* @Description 单例是否线程安全
**/
public class Run {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
// 线程一
UserService bean1 = applicationContext.getBean(UserService.class);
new Thread(()->{
System.out.println(bean1.welcome("张三"));
}).start();
// 线程二
UserService bean2 = applicationContext.getBean(UserService.class);
new Thread(()->{
System.out.println(bean2.welcome("李四"));
}).start();
}
}