synchronized 的使用

1. 开启两个 Runnable

  private Runnable start1Task = new Runnable() {
        @Override
        public void run() {
            while (true) {
                test1Data("start11111");
            }
        }
    };

    private Runnable start2Tack = new Runnable() {
        @Override
        public void run() {
            while (true) {
                test1Data("start22222");
            }
        }
    };

2. 两个加锁方法

private Object object = new Object();
   //线程调用方法一执行完,再线程调用执行方法一
   public synchronized void test1Data(String str) {
       LogUtil.i("TestDataAAA: " + str);
        try {
            //模拟耗时操作
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        LogUtil.i("TestDataBBB: " + str);
    }
    
    //方法二没执行完,另一个线程会进入方法二,开始等待
    public void test2Data(String str) {
        LogUtil.i("TestDataAAA: " + str);
        synchronized (object) {
            try {
                //模拟耗时操作
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LogUtil.i("TestDataBBB: " + str);
        }
    }

3. 测试方法

    private void initView(View view) {
        view.findViewById(R.id.but_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(start1Task).start();
                new Thread(start2Tack).start();
            }
        });
    }

猜你喜欢

转载自blog.csdn.net/u011193452/article/details/129791164