2016-07-04 1 views
3

ソケット接続用に2つのスレッドSocketInとSocketOutを作成しました(どちらもwhile(true)ステートメントで動作しています)。キーボードの入力を待っています。ヌル値を読み込んでいても、スレッドを閉じたり、while(true)を出さないと、次の命令を実行し続けても、それをやり続ける必要があります。いくつかのアドバイス。CSPプログラミングとBlockingQueue S内にスレッドが他のスレッドから入力操作を読み飛ばすようにする

+1

コードを表示してください。私は[割り込み](https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html)を使用すると役立つかもしれないと思います。しかし、これは、どのような方法がブロックされていても中断可能であることを要求します。 – Fildor

+0

あなたは値を提供するのはどうですか?プログラム的には、何かランダムなショーを与えるように、それは続けることができます。しかし、あるコードは役に立ちます。 – GOXR3PLUS

答えて

1

を見てください。あなたは、「コマンド」を受け入れ、あなたのループでのキューを使用することができます。コマンドの一つは、ソケットから入力され、他のコマンドは、キーボードから入力される。

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

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

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

     } else { 
      ... 
     } 
    } 
} 
0

キーボードを読むためにもう1つのスレッドを導入することができます。次に、キーボードリーダーからソケットライター(たとえば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 
     } 
    } 
}); 
関連する問題