日期:2014-05-20  浏览次数:20694 次

一个java多线程问题,求牛人指教
Java code
package test;

public class SyncTest {

    private int x;
    private int y;
    private  void setX (int i) {x=i;}
    private  void setY (int i) {y=i;}
    public void setXY(int i){setX(i); setY(i);}
    public  boolean check() {
        boolean f = (x !=y);
        System.out.println("x="+x+",y="+y);
        return f;
    }

    
    public static void main(String[] args) {
        SyncTest st = new SyncTest();
        
        for (int i=0; i<10; i++)
        {
            Thread t = new Th(i, st);
            t.start();
        }
        
        while (true)
        {
            System.out.println(st.check());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    static class Th extends Thread
    {
        private int i;
        
        SyncTest st ;
        
        public Th(int i, SyncTest st)
        {
            this.i = i;
            this.st = st;
        }

        @Override
        public void run() {
            while (true)
            {
                st.setXY(i);
                java.util.Random random = new java.util.Random();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }

}


以上程序的执行结果如下:
x=1,y=1
false
x=2,y=2
false
x=4,y=4
false
x=5,y=1
false
x=1,y=1
false
x=1,y=3
false
x=7,y=7
false
x=1,y=6
false
x=6,y=0
false
x=3,y=7
false
x=7,y=7
false
不管x、y的值是什么,check方法返回的永远是false,这是为什么???

------解决方案--------------------
Java code

//这样再试一下
public void setXY(int i){
        setX(i); 
        try{Thread.sleep(1);}catch(Exception e){e.printStackTrace();}
        setY(i);
    }