线程间出现不同步现象

package comm;

class Res {
    String name;
    String sex;
}

class Input implements Runnable {
    private Res r;

    public Input(Res r) {
        this.r = r;
    }

    public void run() {
        int x = 0;
        while (true) {

            if (x == 0) {
                r.name = "mike";
                r.sex = "man";
            } else {
                r.name = "丽丽";
                r.sex = "女女女";
            }
            x = (x + 1) % 2;
        }
    }
}

class Output implements Runnable {
    private Res r;

    public Output(Res r) {
        this.r = r;
    }

    public void run() {
        while (true)
            System.out.println(r.name + " , " + r.sex);
    }
}

public class InputOutoutDemo {

    public static void main(String[] args) {

        Res r = new Res();
        Input in = new Input(r);
        Output out = new Output(r);
        Thread t1 = new Thread(in);
        Thread t2 = new Thread(out);
        t1.start();
        t2.start();
    }
}

可能出现的打印结果是

丽丽 , 女女女
mike , man
丽丽 , 女女女
mike , 女女女
丽丽 , man
丽丽 , man
丽丽 , 女女女
丽丽 , 女女女
丽丽 , 女女女
丽丽 , 女女女
mike , man
mike , man
mike , 女女女
丽丽 , 女女女

产生的原因是当输入线程进行输入时,刚刚输入完name,还未来得及输入sex,执行权就被输出线程抢走了,所以输出了mike , 女女女 这样的结果。

你可能感兴趣的:(线程间出现不同步现象)