浏览 1146 次
锁定老帖子 主题:一个线程安全类的示例
该帖已经被评为新手帖
|
|
---|---|
作者 | 正文 |
发表时间:2009-02-15
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)) { newWork.addElement( listOfFiles ); } } 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;} } } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |