我有一個要求,我必須檢查文件夾中是否存在任何文件。如果是,那麼我需要逐一處理它。有了我的基礎知識,我已經到達了我在下面發佈的代碼結構。使用java在n秒內檢查並處理一次
我創建了一個無限循環並檢查文件是否存在於該文件夾中。如果是,那麼我創建一個線程並處理它,否則它會等待一分鐘並再次檢查。
class sample {
synchronized int getNoOfFiles() {
// get number of files in the folder
}
synchronized void openFile() {
// open one file
}
synchronized void getFileContents() {
// get the file content
}
synchronized void processFileContent() {
//performing some operation on file contents
}
synchronized void closeFile() {
//closing the file
}
synchronized void deleteFile() {
//delete the file
}
}
class Test {
public static void main(String args[]) {
int flag=0;
Sample obj = new Sample();
while(1) {
flag = obj.getNoOfFiles();
if(flag) {
for(i=0;i<flag;i++) {
MyThread1 t1 = new MyThread1() {
public void run() {
obj.openFile();
obj.getFileContents();
obj.processFileContent();
obj.closeFile();
obj.deleteFile();
}
};
t1.start();
}
}
else {
try {
Thread.sleep(60000);
}
}
}
}
}
線程沒有得到垃圾收集。所以你的代碼已經在每個循環中創建一個新的線程。即使't1'引用了仍在處理文件的線程,該線程也不會停止運行。一個新的將被實例化,由't1'引用並開始。 – Tobold
噢。所以,我不需要這個for循環(剛剛編輯代碼)。我怎麼能阻止線程創建,直到一個線程完成整個過程。你能幫我嗎 – srinath
你爲什麼要這麼做?如果你創建一個線程,然後等待線程完成,爲什麼要使用併發呢? – Tobold