java 非线程安全_Java线程安全和非线程安全

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入 // 计数器 Counter counter = new Counter(); // 线程数量(1000) int threadCount = 1000; // 用来让主线程等待threadCount个子线程执行完毕 CountDownLatch countDownLatch = new CountDownLatch(thr

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

// 计数器

Counter counter = new Counter();

// 线程数量(1000)

int threadCount = 1000;

// 用来让主线程等待threadCount个子线程执行完毕

CountDownLatch countDownLatch = new CountDownLatch(threadCount);

// 启动threadCount个子线程

for(int i = 0; i < threadCount; i++)

{

Thread thread = new Thread(new MyThread(counter, countDownLatch));

thread.start();

}

try

{

// 主线程等待所有子线程执行完成,再向下执行

countDownLatch.await();

}

catch (InterruptedException e)

{

e.printStackTrace();

}

// 计数器的值

System.out.println(counter.getCount());

}

}

class MyThread implements Runnable

{

private Counter counter;

private CountDownLatch countDownLatch;

public MyThread(Counter counter, CountDownLatch countDownLatch)

{

this.counter = counter;

this.countDownLatch = countDownLatch;

}

public void run()

{

// 每个线程向Counter中进行10000次累加

for(int i = 0; i < 10000; i++)

{

counter.addCount();

}

// 完成一个子线程

countDownLatch.countDown();

}

}

class Counter

{

private int count = 0;

public int getCount()

{

return count;

}

public void addCount()

{

count++;

}

}

上面的测试代码中,开启1000个线程,每个线程对计数器进行10000次累加,最终输出结果应该是10000000。

但是上面代码中的Counter未进行同步控制,所以非线程安全。

输出结果:

9963727

9973178

9999577

9987650

9988734

9988665

9987820

9990847

9992305

9972233

稍加修改,把Counter改成线程安全的计数器:

[java]

class Counter

{

private int count = 0;

public int getCount()

{

return count;

}

public synchronized void addCount()

{

count++;

}

}

class Counter

{

private int count = 0;

public int getCount()

{

return count;

}

public synchronized void addCount()

{

count++;

}

}

上面只是在addCount()方法中加上了synchronized同步控制,就成为一个线程安全的计数器了。再执行程序。

输出结果:

10000000

10000000

10000000

10000000

10000000

10000000

10000000

10000000

10000000

10000000

[1] [2] [3]

test.jsp?url=http%3A%2F%2Fwww.chinaitlab.com%2Fcms%2Fimages%2Flogo14.gif&refer=http%3A%2F%2Fjava.chinaitlab.com%2Fline%2F926892_3.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值