1.未加synchronized关键,造成访问顺序混乱
package thread; /** * @author xiaolong.zhu.baby@qq.com created on 2015/2/6. */ public class Test extends Thread { public void jump() { for (int i = 0; i < 100; i++) { if(i%10==0)
System.out.println(); System.out.print(" "+this.currentThread().getName() + ":" + i + "\t"+" "); } } @Override public void run() { jump(); } public static void main(String[] args) { Test test = new Test(); Thread a = new Thread(test, "A"); Thread b = new Thread(test, "B"); a.start(); b.start(); } }
运行结果:
2. 添加synchronized进行互斥访问可以解决数据不同步的问题
package thread; /** * @author xiaolong.zhu.baby@qq.com created on 2015/2/6. */ public class Test extends Thread { public synchronized void jump() { for (int i = 0; i < 100; i++) { if(i%10==0)
System.out.println(); System.out.print(" "+this.currentThread().getName() + ":" + i + "\t"+" "); } } @Override public void run() { jump(); } public static void main(String[] args) { Test test = new Test(); Thread a = new Thread(test, "A"); Thread b = new Thread(test, "B"); a.start(); b.start(); } }
运行结果:
总结:使用了synchronized可以使一个线程运行完synchronized所修饰的方法,其他需要排队等候,可以保证数据的准确性。