2016-07-04 71 views
3

我创建了2个线程一起工作的套接字连接:SocketIn和SocketOut(它们都在while(true)语句中工作在某些时刻,我需要SocketOut线程停止等待键盘输入,即使他已经读取了一个空值,我仍然需要执行下面的指令,而且我不需要关闭线程或者离开while(true),我不知道该怎么做,所以我需要一些建议。使线程跳转读取输入操作从其他线程

+1

请显示一些代码。我想使用[中断](https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html)可能会有所帮助。但那会要求无论阻止什么方法都是可以中断的。 – Fildor

+0

你怎么提供一个值?像编程式给它一个或什么随机显示它可以继续。有些代码将是有用的,虽然.. – GOXR3PLUS

回答

1

查找到CSP编程和BlockingQueue秒。你可以在你的循环接受“命令”使用队列,一个命令是从插座输入,另一个命令是从键盘输入。

private final BlockingQueue<Command> inputChannel = new SynchronousQueue<>(); 

public void run() { 
    while (true) { 
     Command request = this.inputChannel.take(); 

     if (request instanceof Command.KeyboardInput) { 
      ... 

     } else { 
      ... 
     } 
    } 
} 
0

您可以引入一个线程来阅读键盘。然后添加一些具有从键盘阅读器到套接字写入器的中断的丰富功能的“通道”(例如一些BlockingQueue):

class SocketApp { 
    public static void main(String[] args) throws IOException { 
     ExecutorService pool = Executors.newCachedThreadPool(); 

     URL url = new URL("http://..."); 
     HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
     con.setRequestMethod("POST"); 
     con.setDoOutput(true); 

     OutputStream dst = con.getOutputStream(); 
     InputStream src = con.getInputStream(); 

     // channel between keyboard reader and socket writer 
     BlockingQueue<Integer> consoleToSocket = new ArrayBlockingQueue<>(256); 

     // keyboard reader 
     pool.submit(() -> { 
      while (true) { 
       consoleToSocket.put(System.in.read()); 
      } 
     }); 

     // socket writer 
     pool.submit(() -> { 
      while (true) { 
       dst.write(consoleToSocket.take()); 
      } 
     }); 

     // socket reader 
     pool.submit(() -> { 
      while (true) { 
       System.out.println(src.read()); 
      } 
     }); 
    } 
} 

// Now you can use different features of BlockingQueue. 
// 1. 'poll' with timeout 
// socket sender 
pool.submit(() -> { 
    while (true) { 
     Integer take = consoleToSocket.poll(3, TimeUnit.SECONDS); 
     if (take != null) { 
      dst.write(take); 
     } else { 
      // no data from keyboard in 3 seconds 
     } 
    } 
}); 

// 2. Thread interruption 
// socket sender 
pool.submit(() -> { 
    while (true) { 
     try { 
      Integer take = consoleToSocket.take(); 
      dst.write(take); 
     } catch (InterruptedException e) { 
      // somebody interrupt me wait for keyboard 
     } 
    } 
});