IBM®
跳转到主要内容
    中国 [选择]    使用条款
 
 
Select a scope: Search for:    
    首页    产品    服务与解决方案     支持与下载    个性化服务    
跳转到主要内容

developerWorks 中国  >  Java technology  >

Writing efficient thread-safe classes

Example of a fully functioning thread-safe class

developerWorks

import java.io.*;
import java.util.*;
import java.lang.*;
public class WorkTable {
	private Vector newWork;
	private Vector assignedWork;
	private String dirName;
	class Refresher extends Thread {
		int refreshTime;
		Refresher(int x) {
			super("Refresher");
			refreshTime = x;
		}
		public void run() {
			while(true) {
				if(newWork.isEmpty()) {
					populateTable();
				}
				try { sleep(refreshTime); } catch(Exception e) {}
			}
		}
	}
	WorkTable(String aWorkingDir) {
		newWork = new Vector();
		assignedWork = new Vector();
		dirName = aWorkingDir;
		Refresher r = new Refresher(1000);
		r.setDaemon(true);
		r.start();
	}
	synchronized private void populateTable() {
		File workingDir = new File(dirName);
		String[] listOfFiles = workingDir.list();
		if (listOfFiles.length != 0) {
			for (int i=0; i < listOfFiles.length; i++) {
				if(! assignedWork.contains(listOfFiles[i])) {
					newWork.addElement( listOfFiles[i] );
				}
			}
			notifyAll();
		}
	}
	public void finishWork(String processedFile) {
		File f = new File(processedFile);
f.delete();
		synchronized(this) {
			assignedWork.remove(processedFile);
		}
	}
	public synchronized String getWork(String aThreadID) {
		while(true) {
			if(newWork.isEmpty())
				try { wait(); } catch(Exception e) {}
			else {
				String fileName = (String)newWork.firstElement();
				assignedWork.add(fileName);
				try {
					newWork.removeElementAt(0);
				}
				catch(ArrayIndexOutOfBoundsException ex) {}
				return fileName;
			}
		}
	}
}

Return to the article.

    关于 IBM 隐私条约 联系 IBM 使用条款