我创建了2个线程一起工作的套接字连接:SocketIn和SocketOut(它们都在while(true)语句中工作在某些时刻,我需要SocketOut线程停止等待键盘输入,即使他已经读取了一个空值,我仍然需要执行下面的指令,而且我不需要关闭线程或者离开while(true),我不知道该怎么做,所以我需要一些建议。使线程跳转读取输入操作从其他线程
3
A
回答
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
}
}
});
相关问题
- 1. 从其他线程获取listboxitems:跨线程操作无效
- 2. 从其他线程读取值。
- 3. 从辅助线程读取输入
- 4. 如何从子线程或其他线程获取父线程?
- 5. 在线程中启动作业从其他线程的队列中读取
- 6. 使从其他线程
- 7. 使线程从其他类
- 8. IO操作在其他线程中阻塞我的UI线程?
- 9. 读取来自其他线程
- 10. 从其他线程停止线程
- 11. 读取()操作期间的线程
- 12. 跨线程操作无效:从其创建线程以外的其他线程访问
- 13. 从另一个线程操作线程
- 14. 处理多线程读取输入
- 15. 从其他线程回调
- 16. 如何从其他线程
- 17. 从线程以外的线程访问跨线程操作
- 18. 使用时钟()作为一个线程时间其他线程
- 19. 从其他进程读取和写入
- 20. 多线程写入,一个线程从队列中读取,线程安全
- 21. Android:如何从C++中的其他线程读取资产
- 22. 从其他线程读取复选框状态
- 23. 线程获取已被其他线程获取的ReentrantLock
- 24. 其他线程内的辅助线程
- 25. Java线程监视其他线程
- 26. pthreads:触发其他线程的线程
- 27. c#线程访问其他线程
- 28. 在fork和exec块之间运行的线程其他线程读取
- 29. IN线程安全如何编写地图和其他线程读取
- 30. 从子线程执行外部命令(并读取其输出)
请显示一些代码。我想使用[中断](https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html)可能会有所帮助。但那会要求无论阻止什么方法都是可以中断的。 – Fildor
你怎么提供一个值?像编程式给它一个或什么随机显示它可以继续。有些代码将是有用的,虽然.. – GOXR3PLUS