在Java如何保证方法是线程安全的

  在Java如何保证方法是线程安全的

  废话开篇

  都说Java程序好些,但是我觉得Java编程这东西,没个十年八年的真不敢说自己精通Java编程,由于工作原因,开始转战Java多线程,以前没怎么接触过,所以想留点脚印在这两条路上。

  切入正题

  开门见山,今天看到别人写的一段关于方法是否线程安全的文章,比较简单,但是由于自己也是刚开始入门,所以就迈下了第一步。由于注释还算比较详细,所以就不废话了,直接上code.

  此方法不是线程安全的

  1 /**

  2 * @Title: NotThreadSafeCounter.java

  3 * @Package never.uncategory

  4 * @Description: * The method is not thread-safe, because the

  5 * counter++ operation is not atomic, which means it consists

  6 * more than one atomic operations. In this case, one is

  7 * accessing value and the other is increasing the value by one.

  8 * @author "Never" xzllc2010#gmail.com

  9 * @date Mar 14, 2014 7:44:24 PM

  10 */

  11 /*

  12

  13 */

  14 package never.uncategory;

  15

  16 public class NotThreadSafeCounter extends Thread {

  17

  18 private static int counter = 0;

  19

  20 public void run() {

  21 System.out.println("counter:" + getCount());

  22 }

  23

  24 public static int getCount() {

  25

  26 try {

  27 Thread.sleep(1500);

  28 } catch (Exception e) {

  29 e.printStackTrace();

  30 }

  31 return counter++;

  32

  33 }

  34

  35 public static void main(String[] args) {

  36

  37 for (int i = 0; i < 5; i++) {

  38 new NotThreadSafeCounter()。start();

  39 }

  40 }

  41

  42 }

  View Code

  此方法是线程安全的(synchronized)

  1 /**

  2 * @Title: ThreadSafeCounter.java

  3 * @Package never.uncategory

  4 * @Description: Adding synchronized to this method will makes

  5 * it thread-safe,When synchronized is added to a static method,

  6 * the Class object is the object which is locked.If the method

  7 * is not static, then adding synchronized keyword willsynchronize

  8 * the instance of the class, not the Class object.

  9 * @author "Never" xzllc2010#gmail.com

  10 * @date Mar 14, 2014 8:09:45 PM

  11 */

  12 package never.uncategory;

  13

  14 public class ThreadSafeCounter {

  15

  16 private static int counter = 0;

  17

  18 public void run() {

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值