我想寫一個簡單的視頻操作器,所以每秒幾次我需要啓動一個新線程(當前實現Runnable)來處理當前幀,但我沒有保證每個線程需要多長時間才能完成,因此我想限制可以對處理器的計算機上的數字同時運行的線程數量:隊列線程,如果以前的還沒有完成
Runtime runtime = Runtime.getRuntime();
int nP = runtime.availableProcessors();
但我要保證所有線程都創建的按順序運行,因此不會丟幀。
我還想向用戶顯示完成處理需要多長時間,這取決於在取消作業時剩下的線程數量,以便它們不會以沒有預告片的視頻文件結束。
使用futureTask,Exector或ExecutorService的任意組合可以實現這種可能性嗎?
謝謝。
編輯:
傢伙嗨,對不起啊,這是相當嚴重的措辭。所以我實際上想要做的是獲取框架,執行一些圖像處理,然後將編輯後的素材保存回新文件。此刻我在回放過程中這樣做,因此每個幀在被定時器調用時都會被操作,定時器會啓動一個線程以儘快處理圖像,但取決於此次操作的次數會有所不同。
我當時想確保如果處理花費的時間比只有最大有效數量的線程用於處理的時間間隔長,並且在達到此限制後創建的任何線程仍然處理而不處理丟棄或垃圾收集。
閱讀前3條評論我可以看到這可能是一個效率較低的方法,我想只有一個線程只是爲了保持UI響應將工作,但我不知道如何繼續添加圖像到線程進行處理,而無需使用巨大的列表。我假設它會是這樣的:
在主類:
Timer actionPerformed {
List.add(decodedImage);
}
在運行的類:
run() {
while(timer.isRunning()) {
if(runCount >= list.size()-1) {
try {
Thread.sleep(500);
} catch() {
/* Catchy stuff */
}
} else {
BufferedImage toProcess = list.get(runCount);
/* Do Processing here */
writeImageToStream();
list.remove(runCount);
runCount++;
}
}
}
這是正確的嗎?
編輯2:
所以這是我到目前爲止有:
public class timerEncode {
private long startTime;
ActionListener goAction = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
BufferedImage decoded = getNextImage();
long write_time = System.nanoTime();
new doImages(decoded, write_time).run();
}
};
Timer goTimer = new Timer(40,goAction);
private BufferedImage getNextImage() {
/* Does inconsequential stuff to retrieve image from the stream*/
}
private void recBtnActionPerformed(java.awt.event.ActionEvent evt) {
startTime = System.nanoTime();
goTimer.start();
}
private class doImages implements Runnable {
final BufferedImage image;
final long write_time;
public doImages(BufferedImage image, long write_time) {
this.image = image;
this.write_time = write_time;
}
public void run() {
BufferedImage out = toXuggleType(image, BufferedImage.TYPE_3BYTE_BGR);
/* Other time consuming processy stuff goes here */
/* Encode the frame to a video stream */
writer.encodeVideo(0,out,write_time-startTime, TimeUnit.NANOSECONDS);
}
private BufferedImage toType(BufferedImage source, int type) {
if(source.getType() != type) {
BufferedImage temp = new BufferedImage(source.getWidth(),source.getHeight(),type);
temp.getGraphics().drawImage(source, 0, 0, null);
source = temp;
}
return source;
}
}
}
此工作正常時,圖像處理很簡單,但你很快就會碰到幾十個併發線程試圖做他們的事情,因爲它變得有點複雜,因此我爲什麼要問如何限制線程的併發數量而不放棄任何。我不確定訂單在這種情況下特別重要,因爲我認爲按順序編寫幀會將它們放在正確的位置,因爲每個幀都指定了寫入時間,但這需要測試。
謝謝,我已經採取了你的船上建議約不斷創造新的線程,並試圖改善原來的解決方案帖子。 – drent 2010-08-09 17:18:26