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来同步,否则,线程间全局变量的值会有差异

 

相关文章:

  • 2021-08-26
  • 2021-10-07
  • 2021-12-20
  • 2021-04-26
  • 2021-12-09
  • 2022-12-23
猜你喜欢
  • 2021-10-25
  • 2022-02-09
  • 2021-10-05
  • 2021-11-13
  • 2021-11-17
  • 2021-10-19
相关资源
相似解决方案