多线程 counter++/counter-- 的上下文切换

该代码示例展示了在多线程环境下,直接操作静态计数器counter与在静态方法中操作counter的差异。当两个线程(t1和t2)分别进行增加和减少操作时,不恰当的同步可能导致计数器的结果不正确,这涉及到上下文切换的问题。在没有同步机制的情况下,由于线程切换,可能会丢失更新,从而影响最终的counter值。
摘要由CSDN通过智能技术生成
public class bankSystem {
    static int counter = 1000;
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                decrease(counter);
            }
        },"t1");
       
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                increase(counter);
            }
        },"t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        
        log.debug(String.valueOf(counter));
    }
	    public static void decrease(int counter) {
	        counter--;
	    }
	    public static void increase(int counter) {
	        counter++;
	    }
 }

使用静态方法,对同一个counter进行操作,不会发生上下文切换,而直接在main方法中使用counter++/–,则会大致上下文切换

public class bankSystem {
    static int counter = 1000;
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                counter--;
            }
        },"t1");
       
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                counter++;
            }
        },"t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        
        log.debug(String.valueOf(counter));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值