说我有一个无限的流:
Stream<Socket> stream = Stream.generate(() -> {
try {
return serverSocket.accept();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
我希望能够像这样使用它:
stream.forEach(socket -> {
new Thread(() -> {
socket.getOutputStream().write("Hi there, client.");
});
});
但这似乎不起作用,这可能是因为我误解了Java 8 Streams的一个关键方面。我做错了什么?
答案 0 :(得分:7)
@Andres Riofrio的回答:
stream
.<Runnable>map(socket -> () ->
socket
.getOutputStream()
.write("Hi there, client.")
) // create a Runnable that writes a string to the socket's output stream
.map(Thread::new) // transform each Runnable into a Thread
.forEach(Thread::start) // start each Thread
;
答案 1 :(得分:2)
实际上,我的问题是我忘了启动帖子:
stream.forEach(socket -> {
new Thread(() -> {
socket.getOutputStream().write("Hi there, client.");
}).start();
});