栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

需要帮助来改善Java客户端端口侦听器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

需要帮助来改善Java客户端端口侦听器

有很多不同的方法可以使IO在不同的线程上执行,但是在这种情况下,您可能要使用SwingWorker。

您的代码如下所示:

private final Executor executor = Executors.newSingleThreadExecutor();public void writePacket(final String packet) {  // schedules execution on the single thread of the executor (so only one background operation can happen at once)  //  executor.execute(new SwingWorker<String, Void>()      {        @Override        protected String doInBackground() throws Exception        {          // called on a background thread                    System.out.println("writing out this packet->"+packet+"<-");          System.out.println(packet);          String thePacket = readPacket();  //where the port listener is invoked. return thePacket;         }        @Override        protected void done()        {          // called on the Swing event dispatch thread          try          { final String thePacket = get(); // update GUI with 'thePacket'          }          catch (final InterruptedException e)          { // TODO Auto-generated catch block e.printStackTrace();          }          catch (final ExecutionException e)          { // TODO Auto-generated catch block e.printStackTrace();          }         }      });}private String readPacket() {  String thePacket ="";  String fromServer="";  //Below is the loop that freezes everything.     try   {    while ((fromServer = in.readLine()) != null)     {       if (thePacket.equals(""))         thePacket = fromServer;      else         thePacket = thePacket+newline+fromServer;    }    return thePacket;  //when this happens, all listening should stop.     }   catch (IOException e)   {    e.printStackTrace();    return null;  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/506451.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号