java 加锁使用 synchronized 关键字解决线程不安全问题

public class TestThread5 {
        static  class Counter2 {
            public int count = 0;
            public int count2 = 0;
            //synchronized 关键字进行加锁操作
            //synchronized可以对某个对象进行加锁
            //进入increase方法会尝试加锁 方法执行完毕会解锁
            //加锁之后其他线程调用这个方法会阻塞需要上一个线程执行完后解锁才能继续运行
            synchronized public void increase2() {
                count2++;
            }
            //线程不安全的写法 ->多线程并发执行时产生了逻辑上的错误.
             public void increase() {
                count++;
            }
        }
        public static void main(String[] args) throws InterruptedException {
            Counter2 counter2 = new Counter2();
            Thread t1 = new Thread() {
                @Override
                public void run() {
                    for (int i = 0;i < 50000;i++) {
                        counter2.increase();
                        counter2.increase2();
                    }
                }
            };
            Thread t2 = new Thread() {
                @Override
                public void run() {
                    for (int i = 0;i < 50000;i++) {
                        counter2.increase();
                        counter2.increase2();
                    }
                }
            };
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            //值为 50000 ~ 100000
            System.out.println(counter2.count);
            //值为100000
            System.out.println(counter2.count2);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值