Java - 线程和静态变量 [英] Java - Thread and Static variable

查看:79
本文介绍了Java - 线程和静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始使用 Java 中的线程,我无法对程序的输出进行推理

Just started with threads in java and I can't reason with the output of my program

public class ThreadExample extends Thread{
    private int info;
    static int x = 0;

    public ThreadExample (int info) {
        this.info = info;
    }

    public void run () {
        if ( info == 1 )    {
            x = 3;
            System.out.println(Thread.currentThread().getName() + " " + x);
        } else{
            x = 1;
            System.out.println(Thread.currentThread().getName() + " " + x);
        }
    }

    public static void main (String args []) {
        ThreadExample aT1  = new ThreadExample(1);
        ThreadExample aT2  = new ThreadExample(2);
        aT1.start();
        aT2.start();
        System.err.println(x);
    }
}

输出:

Thread-0 3
Thread-1 1
3

为什么即使第二个线程将静态变量的值更改为 1,它仍然打印 3?

Why does it print 3 even though the 2nd thread changed the value of the static variable to 1?

会不会有 3 个线程同时运行?

Will there be 3 threads running concurrently?

推荐答案

如果您在一个线程中更改变量,则它不会立即(或必要永远)对第二个线程可见,除非您使用某种像 Mutex 这样的同步原语.您还可以使用诸如 AtomicInteger 之类的原子类来确保在一个线程中所做的更改对另一个线程可见.

If you change a variable in one thread it not immediately (or necessary ever) visible to a 2nd thread unless you use some kind of synchronization primitive like a Mutex. You can also use the atomic classes like AtomicInteger to ensure changes made in one thread become visible to the other.

在文档中提供了更多信息.

这篇关于Java - 线程和静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆