對不起,我的游泳池英語。 我有一個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