日期:2014-05-20 浏览次数:20694 次
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(); } } } } }
//这样再试一下 public void setXY(int i){ setX(i); try{Thread.sleep(1);}catch(Exception e){e.printStackTrace();} setY(i); }