Java线程的影响和竞争条件 [英] java threads effect and race condition

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

问题描述

可能重复:
Java线程对静态类的影响

Possible Duplicate:
java threads effect on static classes

考虑以下代码:

    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的最大和最小数量? 什么会导致打印的1张数量发生变化?

there is clearly a race condition. how can i evaluate the maximum and minimum number of 1's that will be printed? what may cause change in the number of 1 printed?

推荐答案

1s的最小数量显然为10,最大数量为20.

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

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.

这篇关于Java线程的影响和竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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