有很多不同的方法可以使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; }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)