首页 > 解决方案 > Android处理程序第一次无法接收消息

问题描述

我创建了两个工作线程并向UI处理程序发送消息,第一次处理程序提前从一个线程收到消息,但后来错过了第二条消息。当我再次尝试时,所有消息都可以接收。为什么第二条消息在第一次丢失?

这是 UI 处理程序:

   handler=new Handler(){
    @Override
    public void handleMessage (Message msg)
    {
        switch (msg.what){

            case 0:{      
                if(msg.arg1==10){
                   //process second thread

                }
                else
                 {//first thread

                 }
            }
            break;
        }
        super.handleMessage(msg);
    }`

这是 thread_one 处理程序:

  void get_list(String Msg,double price){

    class runable implements   Runnable{
        @Override
        public void run() {
            Message msg=HelpedHandle.obtainMessage();
            try {
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                int len =40+Msg.length;
                byte  Data[] =generate_Sokect_header(len,NEW_REQUIRE,id);
                long msglen=Msg.length;
                Data=Concat(Data,longTobyte(msglen)); 
                Data=Concat(Data,doubleTobyte(price));
                Data=Concat(Data,doubleTobyte(0));

                Data=Concat(Data,Msg);
                out.write(Data);
                msg.what =0;
                msg.arg1=-1;

            }
            catch (IOException e){
                msg.what = -1;
            }
            msg.sendToTarget();
        }
        public byte Msg[];
        public double price;
    }
    runable runable1=new runable();
    runable1.Msg=Msg.getBytes();
    runable1.price=price;
    pthreadPool.execute(runable1);

}

这是线程_2:

`void get_context(){
    class runable implements   Runnable{
        @Override
        public void run() {
            while(true) {
                try {
                    DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                    int length = inputStream.read(recive);
                    byte flag[] = new byte[4];
                    System.arraycopy(recive, 0, flag, 0, 4);
                    byte len[]= new byte[8];
                    System.arraycopy(recive,8, len, 0, 8);
                    long check=byteTolong(len);
                    if(length!=check)
                        continue;   
                            Message msg = handler.obtainMessage();
                            msg.what=0;
                            msg.arg1 = 10;                  
                            msg.setData(bundle);
                            msg.sendToTarget();
                   }
             }catch{}
     }
   } 
 pthreadPool.execute(new runable());
}

标签: javaandroid

解决方案


推荐阅读