知行合一

享受过程 漠视结果

导航

android 多线程 示例

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

 

posted on 2015-10-16 14:07  项羽  阅读(346)  评论(0编辑  收藏  举报