论坛首页 入门技术论坛

一个线程安全类的示例

浏览 1148 次
该帖已经被评为新手帖
作者 正文
   发表时间:2009-02-15  
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))
    {
     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;}
}
}
}
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics