package com.leetcode.multithreading.licm;
/**
* @description: aqs
* @author: licm
* @create: 2021-07-26 10:21
**/
/**
* 通过synchronized 实现线程安全
*
* i++是三步操作 所以用volitile不可以
*/
public class NotSafe {
private long count = 0;
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
//count进行累加
public synchronized void incCount() {
count++;
}
//线程
private static class Count extends Thread {
private NotSafe simplOper;
public Count(NotSafe simplOper) {
this.simplOper = simplOper;
}
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
simplOper.incCount();
}
}
}
public static void main(String[] args) throws InterruptedException {
NotSafe simplOper = new NotSafe();
//启动两个线程
Count count1 = new Count(simplOper);
Count count2 = new Count(simplOper);
count1.start();
count2.start();
Thread.sleep(50);
System.out.println(simplOper.count);//20000?
}
}
不会,我可以学;落后,我可以追赶;跌倒,我可以站起来!
版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.51cto.com/u_12550160/3206499,作者:小傻孩丶,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。