酷酷啦啦xsx 2015-07-22 02:29 采纳率: 100%
浏览 1575
已采纳

java队列请教,大神快来指点下

我socket服务器与客户端通信,使用BlockQueue来实现生产和消费

这个语句是在已连接客户端列表中查找已选择的客户端,并获取这个客户端的发送队列,将发送文本框的数据发送到BlockQueue中,也就是数据的生产者
for (StreamFactory currentStream : myMainFram.myStreamFactory) {

            if(currentStream.getDescsString().equals(ClientListJPanel.getItemAt(myServer.getSelectedClient()))){

                byte[] temp = NetSendArea.getText().getBytes();

                for (byte a : temp) {

                    try {       

                        currentStream.getMybBlockQueueTool().getTxQueue().put(a);;

                    } catch (InterruptedException e) {

                        // TODO Auto-generated catch block

                        e.printStackTrace();

                    }

                    System.out.println("原数据"+a);

                }

            }

        }

这个客户端里面的线程,读取发送队列是不是有数据,如果有,用这个客户端的IO流发送数据
while(true){

            Byte temp = null;

            try {

                temp = myBlockQueueTool.getTxQueue().poll(10, TimeUnit.MILLISECONDS);

            } catch (InterruptedException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            if(temp != null){

                System.out.println(temp.byteValue());

                try {

                    myiInOutPutStream.getMyoutputStream().write(temp.byteValue());

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }



            }

            else {

                break;

            }

        }

现在现象是,我在发送文本框输入“张雄”,这俩汉字内码是
张 D5C5 雄D0DB

程序打印的数据:
不正常的时候

原数据-43
-43
原数据-59
原数据-48
原数据-37
-48
-37
-59

正常的时候
原数据-43
原数据-59
原数据-48
原数据-37
-43
-59
-48
-37

queue好像是线程安全的,为什么会出现这个现象,从队列读取的数据顺序不是我放进去的顺序,导致发送出去的汉字不对

  • 写回答

1条回答 默认 最新

  • threenewbee 2015-07-22 05:24
    关注

    你是加锁了,但是你只同步了单个的字符,而没有将他们视作整体。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记