本篇内容主要讲解“java两个线程对变量进行加1操作实例分析”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java两个线程对变量进行加1操作实例分析”吧!
1--错误的常规写法
public static int i=0;
public static void add(){
i=i+1;
action();
}
public static void action(){
System.out.println("==>"+Thread.currentThread().getName()+":"+i);
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(SysUserServiceImpl::add,"t1");
Thread t2= new Thread(SysUserServiceImpl::add,"t2");
t1.start();
t2.start();
}
运行结果==>
==>t1:1
==>t2:2
==>t1:2
==>t2:1
==>t1:2
==>t2:2
每次运行结果不一致,多线程环境下,t1对共享内存中的i进行+1操作,但未将值刷新到主内存,此时恰好t2也对i取到还是0进行+1操作,使得最后结果i都为1,同理t1处理完为1,t2处理完为2。多次运行结果都不一致。
改进方法1 --同步锁
public class ThreadException {
public static volatile int i=0;
public static void add(){
synchronized (ThreadException.class){
i=i+1;
action();
}
}
public static void action(){
System.out.println("==>"+Thread.currentThread().getName()+":"+i);
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(ThreadException::add,"t1");
Thread t2= new Thread(ThreadException::add,"t2");
t1.start();
t2.start();
}
}
优点:实现简单
缺点:加锁粒度大,性能低下,分布式环境,多JVM条件,synchronized失效,synchronized 只是本地锁,锁的也只是当前jvm下的对象,在分布式场景下,要用分布式锁
改进方法2 AtomicInteger
public class ThreadException { private static AtomicInteger num = new AtomicInteger(0); public static void add(){ int i = num.getAndIncrement(); action(i); } public static void action(int i){ System.out.println("由"+i+"==>"+Thread.currentThread().getName()+":"+num); } public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(ThreadException::add,"t1"); Thread t2= new Thread(ThreadException::add,"t2"); t1.start(); t2.start(); }}
改进方法3 lock
public class ThreadException {
public static volatile int i=0;
public static void action(){
System.out.println("==>"+Thread.currentThread().getName()+":"+i);
}
static Lock lock=new ReentrantLock();
public static void inc() {
lock.lock();
try {
Thread.sleep(1);
i=i+1;
action();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(ThreadException::inc,"t1");
Thread t2= new Thread(ThreadException::inc,"t2");
t1.start();
t2.start();
}
}
分布式锁:保证多个节点同步执行
实现方案:1。基于数据库,2.基于redis缓存,3.基于zookeeper
到此,相信大家对“java两个线程对变量进行加1操作实例分析”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。