简体   繁体   中英

java threads effect on static classes

consider the following code:

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();
}

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

How is it possible to evaluate the max and min appearances of "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.

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.

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.

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

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).

The min amount of 1s is obviously 10, the max amount will be 20.

20 because worst case will be that both threads reach

while (y[0] < 10)

at the same time every time, and then again reach

++y[0];

also at the same time every time, which will render one of the increments lost.

Whether or not the class is static does not play any role here.

While the ThreadTest.y variable is not static (and it shouldn't be), it is filled with a reference to the same array for all you threads . That is where your synchronization bug is: in main you should not be giving both threads the same array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM