多线程 handler 使用

1.子线程使用handler postdelay;

在主线程里,搞定写数据;
发现,只写密码块不行,必须写了那个前面的,才可以,写后面的;

 public void initCardFromNew() {
//        executorWriteService = Executors.newScheduledThreadPool(4);
//        executorWriteService.scheduleAtFixedRate(initCardRunable, 20, 60, TimeUnit.MILLISECONDS);
//        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
//        singleThreadExecutor.execute(initCardRunable);

     handler.post(initCardRunable);

    }
    Handler handler = new Handler();
    private Runnable initCardRunable = new Runnable() {
        @Override
        public void run() {

            if (curretnBlock < 64) {

                sectorIndex = curretnBlock / 4;
                if (curretnBlock % 4 != 3) {
                    blockInde = curretnBlock % 4;//
                    Log.e("sjt", "写入数据块 第" + sectorIndex + "扇区第" + blockInde + "块数据");
                    onWrite(Constant.Datablock0_2, sectorIndex, blockInde);//写数据块
                } else {
                    Log.e("sjt", "写入秘钥块 第" + sectorIndex + "扇区第" + 3 + "块数据");
                    onWrite(Constant.CCKeyAB, sectorIndex, 3);//写密码块
                }
                handler.postDelayed(this, 50);
                curretnBlock++;
            } else {
                curretnBlock = 0;
              //  executorService.shutdown();//关闭读写
            }
        }
    };

线程池操作,必须要先写数据块,在写密码块;

  public void initCardFromNew() {
        executorWriteService = Executors.newScheduledThreadPool(15);
        executorWriteService.scheduleAtFixedRate(initCardRunable, 20, 50, TimeUnit.MILLISECONDS);
//        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
//        singleThreadExecutor.execute(initCardRunable);

    // handler.post(initCardRunable);

    }
    Handler handler = new Handler();
    private Runnable initCardRunable = new Runnable() {
        @Override
        public void run() {

            if (curretnBlock < 64) {

                sectorIndex = curretnBlock / 4;
                if (curretnBlock % 4 != 3) {
                    blockInde = curretnBlock % 4;//
                    Log.e("sjt", "写入数据块 第" + sectorIndex + "扇区第" + blockInde + "块数据");
                    onWrite(Constant.Datablock0_2, sectorIndex, blockInde);//写数据块
                } else {
                    Log.e("sjt", "写入秘钥块 第" + sectorIndex + "扇区第" + 3 + "块数据");
                    onWrite(Constant.CCKeyAB, sectorIndex, 3);//写密码块
                }
               // handler.postDelayed(this, 50);
                curretnBlock++;
            } else {
                curretnBlock = 0;
                executorService.shutdown();//关闭读写
            }
        }
    };

你可能感兴趣的