多线程调用类的静态方法

调用类的静态方法,不涉及到全局变量时

import java.util.HashMap;

public class SheepThread implements Runnable {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        Mower.mow();
    }
    public static void main(String[] args) {
        HashMap<Integer,String> map = new HashMap<>();
        map.put(0,"喜羊羊");
        map.put(1,"懒羊羊");
        map.put(2,"沸羊羊");
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(new SheepThread());
            thread.setName(map.get(i%3)+i);
            thread.start();
        }
    }
}


public class Mower {
    public static int i = 0;
    public static void mow() {
        int sum = 0;
        System.out.println("************** 当前线程"+ Thread.currentThread());
        for (int i = 0; i < 10; i++) {
            System.out.print("小羊收获 " + i + " 斤草. ");
            sum += i;
        }
        if (sum != 45) {
            System.out.println("Thread error!");
            System.exit(0);
        }
        System.out.println("************** "+ Thread.currentThread() + "收集了" + sum +"斤青草");
    }
}

运行结果

在这里插入图片描述
实际执行的结果显示各个线程对静态方法的访问是交叉执行的,但是这并不影响各个线程静态方法中小羊对青草收集总和的统计。

调用类的静态方法,涉及到全局变量时

import java.util.HashMap;

public class SheepThread implements Runnable {
    @Override
    public void run() {
        // TODO Auto-generated method stub
//        Mower.mow();
        try {
            Mower.calGrassCake();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        HashMap<Integer,String> map = new HashMap<>();
        map.put(0,"喜羊羊");
        map.put(1,"懒羊羊");
        map.put(2,"沸羊羊");
        for (int i = 0; i < 1000; i++) {
            Thread thread = new Thread(new SheepThread());
            thread.setName(map.get(i%3)+i);
            thread.start();
        }
        Thread.sleep(1000);
        System.out.println("************** 慢羊羊统计一共要"+Mower.i+"个青草蛋糕");
    }
}


public class Mower {
    public static int i = 0;

    //统计小羊要吃的青草蛋糕
    public static void calGrassCake() throws InterruptedException {
        System.out.println(Thread.currentThread() +" 要一个蛋糕");
        Thread.sleep(1);
        i++;
        System.out.println("小计:一共要"+i+"个青草蛋糕");
    }
}

运行结果

在这里插入图片描述
不正确

修改

对Mower类的calGrassCake()方法加锁

//统计小羊要吃的青草蛋糕
    public synchronized static void calGrassCake() throws InterruptedException {
        System.out.println(Thread.currentThread() +" 要一个蛋糕");
        Thread.sleep(1);
        i++;
        System.out.println("小计:一共要"+i+"个青草蛋糕");
    }

结果

在这里插入图片描述
结果正确。

总结

静态方法是否引起线程安全问题主要看该静态方法是否对全局变量(静态变量static member)进行修改操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值