public class MyRun implements Runnable { int count = 1000; @Override public void run() { while (true) { if (count > 0) { Log.e("", Thread.currentThread().getName() + "|" + "running"); synchronized (this) { count--; Log.e("", Thread.currentThread().getName() + "|" + count); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } else { break; } } Log.e("", Thread.currentThread().getName() + "|" + "end"); } }
MyRun myRun = new MyRun(); new Thread(myRun, "aaa").start(); new Thread(myRun, "bbb").start(); new Thread(myRun, "ccc").start();
总结:
多线程访问同一个全局变量时,要使用synchronized来同步,否则,线程间全局变量的值会有差异