各类变量的线程安全问题
成员变量的线程安全问题
成员变量的线程是否安全需要分情况而定:
- 如果成员变量没有被共享,那么就没有线程安全问题
- 如果它被共享了,根据它们的状态是否能够改变,又分为下面的两种情况:
- 如果静态变量没有被共享,那么就没有线程安全问题
- 如果它被共享了,根据它们的状态是否能够改变,又分为下面的两种情况:
- 如果只是执行读操作,那么也不存在线程安全问题
- 如果执行了读写操作,则读写操作的代码段就是临界区,需要考虑线程安全问题
局部变量的线程安全问题
- 局部变量是线程安全的
- 如果是局部变量引用的对象,则需要分情况讨论:
- 如果对象未逃离方法的作用范围,则不存在线程安全问题
- 否则,需要考虑线程安全问题
分析变量的线程安全问题
成员变量
对于成员变量而言,多个线程操作的是同一个对象,那么就必须要考虑线程安全问题。
public class ThreadUnsafe {ArrayList<String> list = new ArrayList<>();public void method1(int loopNumber) {for (int i = 0; i < loopNumber; i++) {// { 临界区, 会产生竞态条件method2();method3();// } 临界区}System.out.println(list.size());}private void method2() {list.add("1");}private void method3() {list.remove(0);}static final int THREAD_NUMBER = 2;static final int LOOP_NUMBER = 200;public static void main(String[] args) {ThreadUnsafe test = new ThreadUnsafe();for (int i = 0; i < THREAD_NUMBER; i++) {new Thread(() -> {test.method1(LOOP_NUMBER);}, "Thread" + i).start();}}}


Thread-0还未add,此时list.size()==0,Thread-1就调用了list的remove方法,所以导致异常的抛出。
局部变量
public class ThreadSafe {public final void method1(int loopNumber) {ArrayList<String> list = new ArrayList<>();for (int i = 0; i < loopNumber; i++) {method2(list);method3(list);}System.out.println(list.size());}private void method2(ArrayList<String> list) {list.add("1");}private void method3(ArrayList<String> list) {list.remove(0);}static final int THREAD_NUMBER = 2;static final int LOOP_NUMBER = 200;public static void main(String[] args) {ThreadSafe test = new ThreadSafe();for (int i = 0; i < THREAD_NUMBER; i++) {new Thread(() -> {test.method1(LOOP_NUMBER);}, "Thread" + i).start();}}}


由于Thread-0和Thread-1操作的对象是两个不同的对象,因为两个线程压根操作的不是一个对象,所以局部变量是不存在线程安全问题的。
思考: 局部变量是否真的线程安全?如果把method2或者method3的private修改为public,是否可能会存在线程不安全的隐患?
如果ThreadSafe类的子类重写了method2或者method3的方法,并且在其中开启了一条线程去进行list.remove操作,那么可能存在线程安全问题。如:
class ThreadSafeSubClass extends ThreadSafe{@Overridepublic void method3(ArrayList<String> list) {new Thread(()->{list.remove(0);}).start();}}

因此method2和method3修饰为private而不修饰为public是有原因的,就是为了让子类不要继承这个方法,免得子类重写这个方法后乱搞,搞到线程不安全。
注意: 从上面的例子可以看出 private 或 fifinal 提供【安全】的意义所在。
常见的线程安全类

值得注意的是,这里说的线程安全类是指多个线程调用它们的实例对象的同一个方法时的线程安全,如:
Hashtable table = new Hashtable();new Thread(()->{table.put("key", "value1");}).start();new Thread(()->{table.put("key", "value2");}).start();
但是,如果它们的多个方法组合在一起就不是线程安全了,比如下面这段代码:
Hashtable table = new Hashtable();// 线程1,线程2if( table.get("key") == null) {table.put("key", value);}
为什么线程不安全,可以看下面这个图:
在线程1发生上下文切换时,这时候线程1记住了get(“key”)==null,然后线程2也到了get(“key”)==null,然后put进去,后面又切换到线程1,但是前面线程1记住了get(“key”)==null,于是又执行了一次put,导致整段码执行下来不符合想要“只put一次”的目标。其实就是说,线程安全类的方法是一个原子,但是它们组合在一起就不是一个原子了。
案例分析
案例1
public class MyServlet extends HttpServlet {// 是否安全?Map<String,Object> map = new HashMap<>();// 是否安全?String S1 = "...";// 是否安全?final String S2 = "...";// 是否安全?Date D1 = new Date();// 是否安全?final Date D2 = new Date();public void doGet(HttpServletRequest request, HttpServletResponse response) {}}
问题分析:
HttpServlet是运行在tomcat环境下的,因此只有一个实例,会被多个线程共享。
- HashMap不是线程安全类,所以不是线程安全
- String是线程安全类,因此是线程安全的
- String是线程安全,那么final String也是线程安全
- Date D1 = new Date()不是线程安全的
final Date D2 = new Date()不是线程安全的,但是final修饰只是D2引用所指的对象不能改变,但不能确保这个对象的内容不被修改
案例2
public class MyServlet extends HttpServlet {// 是否安全?private UserService userService = new UserServiceImpl();public void doGet(HttpServletRequest request, HttpServletResponse response) {userService.update(...);}}public class UserServiceImpl implements UserService {// 记录调用次数private int count = 0;public void update() {// ...count++;}}
问题分析:
MyServlet类也是在tomcat中运行,也是单例,因此userService也是被多个线程共享的。而其成员变量count是被共享的,由于在update中count++,导致没有对count进行并发保护,所以这是线程不安全的。案例3
@Aspect@Componentpublic class MyAspect {// 是否安全?private long start = 0L;@Before("execution(* *(..))")public void before() {start = System.nanoTime();}@After("execution(* *(..))")public void after() {long end = System.nanoTime();System.out.println("cost time:" + (end-start));}}
问题分析:
在Spring环境中,所有类都是单例的,因此start是被所有线程共享的,从而导致start可能会被多个线程不同步修改,因此 start成员变量 是线程不安全的。所以最好就是将 start 作为局部变量,这样就不会存在线程安全问题了。案例4
```java public class MyServlet extends HttpServlet { // 是否安全? private UserService userService = new UserServiceImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response) { userService.update(…); } } public class UserServiceImpl implements UserService { // 是否安全? private UserDao userDao = new UserDaoImpl();
public void update() { userDao.update(); } }
public class UserDaoImpl implements UserDao { public void update() { String sql = “update user set password = ? where username = ?”; // 是否安全? try (Connection conn = DriverManager.getConnection(“”,””,””)){ // … } catch (Exception e) { // … } } }
问题分析:<br />Connection连接是在方法中创建的,是一个局部变量,因此它是线程安全的。成员变量userDao由于没有内容可以修改(UserDao类没有成员变量),因此userDao和不可修改其内容有着一样的妙处,所以是线程安全的。而对于成员变量userService,虽然它具有一个属性userDao,但是由于它是private修饰的,也没有方法可以修改userDao,因此成员变量userService也是线程安全的。<a name="JDS3f"></a>## 案例5```javapublic class MyServlet extends HttpServlet {// 是否安全?private UserService userService = new UserServiceImpl();public void doGet(HttpServletRequest request, HttpServletResponse response) {userService.update(...);}}public class UserServiceImpl implements UserService {// 是否安全?private UserDao userDao = new UserDaoImpl();public void update() {userDao.update();}}public class UserDaoImpl implements UserDao {// 是否安全?private Connection conn = null;public void update() throws SQLException {String sql = "update user set password = ? where username = ?";conn = DriverManager.getConnection("","","");// ...conn.close();}}
问题分析:
在本例中,Connection是一个成员变量,它被多个线程同时访问,并且会执行 conn.close() 修改它,因此它是线程不安全的。这样一来,userDao也不是线程安全,同样,userService也不是线程安全。
案例6
public class MyServlet extends HttpServlet {// 是否安全?private UserService userService = new UserServiceImpl();public void doGet(HttpServletRequest request, HttpServletResponse response) {userService.update(...);}}public class UserServiceImpl implements UserService {public void update() {UserDao userDao = new UserDaoImpl();userDao.update();}}public class UserDaoImpl implements UserDao {// 是否安全?private Connection = null;public void update() throws SQLException {String sql = "update user set password = ? where username = ?";conn = DriverManager.getConnection("","","");// ...conn.close();}}
问题分析:
注意对比案例5,这里把userDao变成局部变量了,因此Connection就是线程安全的了。而userService也因此没有成员变量,因此也是线程安全的。
案例7
public abstract class Test {public void bar() {// 是否安全?SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");foo(sdf);}public abstract foo(SimpleDateFormat sdf);public static void main(String[] args) {new Test().bar();}}
问题分析:
在本例中,foo是一个抽象方法,它的实现是不确定的,因此可能它的某个实现会启动一条新的线程去用到sdf,从而导致sdf不是线程安全的。
案例8
private static Integer i = 0;public static void main(String[] args) throws InterruptedException {List<Thread> list = new ArrayList<>();for (int j = 0; j < 2; j++) {Thread thread = new Thread(() -> {for (int k = 0; k < 5000; k++) {synchronized (i) {i++;}}}, "" + j);list.add(thread);}list.stream().forEach(t -> t.start());list.stream().forEach(t -> {try {t.join();} catch (InterruptedException e) {e.printStackTrace();}});log.debug("{}", i);}
问题分析:
同String一样,Integer也是不可变类,单i++之后,i指向了另外一个对象,因此两个线程获取对象 i 的锁不是同一个对象了,所以导致 synchronized (i) 不起作用,因此是线程不安全的。因此可以改进为下面这样就是线程安全的了:
@Slf4j(topic = "c.Test")public class Test {private static Integer i = 0;static Object obj = new Object();public static void main(String[] args) throws InterruptedException {List<Thread> list = new ArrayList<>();for (int j = 0; j < 2; j++) {Thread thread = new Thread(() -> {for (int k = 0; k < 5000; k++) {synchronized (obj) {i++;}}}, "" + j);list.add(thread);}list.stream().forEach(t -> t.start());list.stream().forEach(t -> {try {t.join();} catch (InterruptedException e) {e.printStackTrace();}});log.debug("{}", i);}}
我们只需要让线程持有同一个对象 obj 的锁才能确保i++的线程安全。
经典问题
抢票问题
@Slf4j(topic = "c.Ticket")public class Ticket {// Random 为线程安全static Random random = new Random();// 随机 1~5public static int randomAmount() {return random.nextInt(5) + 1;}public static void main(String[] args) {TicketWindow ticketWindow = new TicketWindow(2000);List<Thread> list = new ArrayList<>();// 用来存储买出去多少张票,Vector是线程安全的listList<Integer> sellCount = new Vector<>();for (int i = 0; i < 3000; i++) {Thread t = new Thread(() -> {// 分析这里的竞态条件try {//模拟买票延迟Thread.sleep(randomAmount());} catch (InterruptedException e) {e.printStackTrace();}int count = ticketWindow.sell(randomAmount());sellCount.add(count);});list.add(t);t.start();}list.forEach((t) -> {try {//需要等待所有线程结束后再统计票数t.join();} catch (InterruptedException e) {e.printStackTrace();}});// 买出去的票求和log.debug("selled count:{}", sellCount.stream().mapToInt(c -> c).sum());// 剩余票数log.debug("remainder count:{}", ticketWindow.getCount());// 剩余票数+卖出去票数log.debug("sum:{}", (sellCount.stream().mapToInt(c -> c).sum() + ticketWindow.getCount()));}}class TicketWindow {private int count;public TicketWindow(int count) {this.count = count;}public int getCount() {return count;}public int sell(int amount) {if (this.count >= amount) {this.count -= amount;return amount;} else {return 0;}}}

可以看到,卖出的票和剩余的票居然不等于总票数2000,明显存在线程安全问题。原因就在于ticketWindow 对象的 count 字段是线程共享的,多个线程在 sell 方法对该对象的 count 对象进行读写操作,又没有对它进行并发保护,所以会导致线程不安全。可以对 ticketWindow 对象上锁解决,如下所示:
public synchronized int sell(int amount) {if (this.count >= amount) {this.count -= amount;return amount;} else {return 0;}}

synchronized 加在方法上面其实就是 synchronized (this){ … },多个线程同时操作ticketWindow 对象的count,只有获得对象锁的线程才能操作 count 字段。
转账问题
@Slf4j(topic = "c.Transfer")public class Transfer {// Random 为线程安全static Random random = new Random();// 随机 1~100public static int randomAmount() {return random.nextInt(100) + 1;}public static void main(String[] args) throws InterruptedException {Account a = new Account(1000);Account b = new Account(1000);Thread t1 = new Thread(() -> {for (int i = 0; i < 1000; i++) {a.transfer(b, randomAmount());}}, "t1");Thread t2 = new Thread(() -> {for (int i = 0; i < 1000; i++) {b.transfer(a, randomAmount());}}, "t2");t1.start();t2.start();t1.join();t2.join();// 查看转账2000次后的总金额log.debug("total:{}", (a.getMoney() + b.getMoney()));}}class Account {private int money;public Account(int money) {this.money = money;}public int getMoney() {return money;}public void setMoney(int money) {this.money = money;}public void transfer(Account target, int amount) {if (this.money > amount) {this.setMoney(this.getMoney() - amount);target.setMoney(target.getMoney() + amount);}}}

可以看到,转账转着转着就两个账号的余额不等于2000了,也是存在明显的线程安全问题。
思考: 下面这样修改可以确保线程安全吗?
public synchronized void transfer(Account target, int amount) {if (this.money > amount) {this.setMoney(this.getMoney() - amount);target.setMoney(target.getMoney() + amount);}}
上面这样修改其实是不能确保线程安全的,this 只是当前对象的money,但是 transfer 方法里面涉及到两个对象,一个是this(即调用 transfer 方法的当前对象),另一个是 target 对象,synchronized(this) 很明显不能确保 this 和 target 的money的线程安全,因此我们需要锁住的是 target 和 this 共同拥有的对象:Account.Class 。如:
public void transfer(Account target, int amount) {synchronized (Account.class){if (this.money > amount) {this.setMoney(this.getMoney() - amount);target.setMoney(target.getMoney() + amount);}}}
再次运行:
