对不起,我的游泳池英语。 我有一个javaFx应用程序需要连接到许多套接字服务器(超过40),这是在Android手机开始。 当连接到服务器时,我建立一个线程来保存长连接,每隔600毫秒服务器将SCREENSHOT(二进制)发送到我的应用程序。 javaFx应用程序不能是服务器。 下面是部分代码:如何在Socket长连接中保持CPU使用率较低
while (ScreenMonitorService.isConnectionAll()){
Future<Image> f = ThreadPoolUtil.getThreadPool().submit(new Callable<Image>() {
@Override
public Image call() throws Exception {
return readImage(inputStream, outputStream);
}
});
Image fxImage = f.get();
Platform.runLater(()->{
device.getImageView().setImage(fxImage);
});
//what readImage do
private synchronized Image readImage(InputStream inputStream, OutputStream outputStream) throws IOException {
try {
Thread.sleep(700);<==== This is the now solution for high cpu performtion , but it doesn't work
} catch (InterruptedException e) {
logger.error("=====> error", e);
}
int fileLen = readInt(inputStream);
int readLength = fileLen;
int tempLength = 0;
int n;
byte[] bt = new byte[readLength];
ByteArrayOutputStream bout = new ByteArrayOutputStream();
while ((n = inputStream.read(bt,0,readLength)) > 0) {
tempLength += n;
readLength = tempLength + n > fileLen ? fileLen - tempLength : readLength;
bout.write(bt,0,n);
}
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
BufferedImage image = ImageIO.read(bin);
Image fxImage = SwingFXUtils.toFXImage(image,null);
writeInt(outputStream,1);
return fxImage;
}
我知道这是繁忙的,瓦亭,这使得坏CPU的性能。 我已经使用nio | notify/wait | blockqueue尝试解决问题,但失败。 可能有人可以给我一些建议来解决这个问题,谢谢。
我已经剖析了代码。 – alongsea2
转换成本约为200毫秒。 – alongsea2
也感谢您的建议 – alongsea2