Java 学习笔记之 方法内的临时变量是线程安全

时间:2021-01-28 18:16:05

方法内的临时变量是线程安全:

 

方法内部的私有变量,是线程安全的。

public class HasSelfPrivateNum {
    public void addI(String username) {
        try {
            int num = 0;
            if (username.equals("a")){
                num = 100;
                System.out.println("a set over!");
                Thread.sleep(2000);
            } else {
                num = 200;
                System.out.println("b set over!");
            }
            System.out.println(username + " num = " + num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class HasSelfPrivateNumThreadA extends Thread{
    private HasSelfPrivateNum numRef;

    public HasSelfPrivateNumThreadA(HasSelfPrivateNum numRef) {
        super();
        this.numRef = numRef;
    }

    @Override
    public void run() {
        super.run();
        numRef.addI("a");
    }
}

public class HasSelfPrivateNumThreadB extends Thread {
    private HasSelfPrivateNum numRef;

    public HasSelfPrivateNumThreadB(HasSelfPrivateNum numRef) {
        super();
        this.numRef = numRef;
    }

    @Override
    public void run() {
        super.run();
        numRef.addI("b");
    }
}

public class ThreadRunMain {
    public static void main(String[] args) {
        testHasSelfPrivateNumThread();
    }
    public static void testHasSelfPrivateNumThread(){
        HasSelfPrivateNum numRef = new HasSelfPrivateNum();
        HasSelfPrivateNumThreadA athread = new HasSelfPrivateNumThreadA(numRef);
        athread.start();
        HasSelfPrivateNumThreadB bthread = new HasSelfPrivateNumThreadB(numRef);
        bthread.start();
    }
}

运行结果:

Java 学习笔记之 方法内的临时变量是线程安全