您好,欢迎访问一九零五行业门户网

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操作实例分析的详细内容。
其它类似信息

推荐信息