java线程对静态类的影响 [英] java threads effect on static classes

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

问题描述

考虑以下代码:

static class ThreadTest extends Thread {
    int x;
    int[] y;

    public ThreadTest(int x, int[] y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public void run() {

        while (x< 10) {
            ++x;
            System.out.print("0");
        }
        while (y[0] < 10) {
            ++y[0];
            System.out.print('1');
        }
    }
}

public static void main(String args[]) {
    int x = 0;
    int[] y = new int[1];
    y[0] = 0;

    Thread A = new ThreadTest(x, y);
    Thread B = new ThreadTest(x, y);

    B.start();
    A.start();
}

将打印多少个1和多少个0?
我怎样才能确保每次程序运行时1的数量都相同?
注意该类是静态

how many 1's and how many 0's will be printed? how can I ensure that the number of 1's will be the same every time the program runs? notice that the class is static

如何评估1的最大和最小外观?

How is it possible to evaluate the max and min appearances of "1"?

推荐答案

目前,您的代码包含竞争条件,因为两个线程正在修改相同的 y 数组。这意味着打印的1的数量是不确定的。

Currently, your code contains a race condition since the two threads are modifying the same y array. This means that the number of 1s that get printed is indeterminate.


我怎样才能确保每次的1的数量是相同的程序运行?

how can I ensure that the number of 1's will be the same every time the program runs?

你需要在两个线程之间引入同步。

You need to introduce synchronization between the two threads.

这可以通过多种方式完成。 Java中最常见的一种是在修改和/或读取共享状态的代码周围使用 synchronized 块。

This can be done in a variety of ways. The most common one in Java is to use a synchronized block around the code that modifies and/or reads shared state.

另一种方法是用一个 int [1] 数组/api/java/util/concurrent/atomic/AtomicInteger.html\"rel =nofollow noreferrer> AtomicInteger 。这对于这种特殊情况非常有效。

An alternative way is to replace the int[1] array with a single AtomicInteger. This would work pretty well for this particular case.


注意该类是静态的

notice that the class is static

这个类是否 static 在这里完全无关紧要。 所有这意味着 ThreadTest 的实例没有隐式引用到外部类的一个实例。它与 ThreadTest 的实例之间的状态共享无关(我认为这就是你在这里所暗示的)。

Whether the class is static is totally irrelevant here. All it means is that an instance of ThreadTest has no implicit reference to an instance of the outer class. It has nothing to do with the sharing of state between instances of ThreadTest (which I think is what you're implying here).

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

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