上一篇用python实现的,用到map函数比较方便,用java实现起来可就没那么简单了,需要考虑线程共享数据问题、同步问题
class RunCmd implements Runnable
{
int index =0;//全局变量,线程共享数据,否则每个线程都会执行一次同一条命令
List<File> molsList = new ArrayList<File>();
public RunCmd()
{
File f = new File("/map/ph");
getFileList(f);
}
private void getFileList(File f)
{
File[] filePaths = f.listFiles();
for (File mol : filePaths)
{
if (mol.getName().endsWith("_omega2.mol2"))
{
molsList.add(mol);
}
}
}
public void run()
{
File file = null;
while(index < molsList.size())
{
file=molsList.get(index);
index++;
System.out.println(Thread.currentThread().getName());
String cmd = "···";
System.out.println(cmd);
try
{
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();//在cmd执行时其他线程需要等待到其执行完毕,否则会将任务全部提交到后台
}
catch(IOException e){}
catch(InterruptedException i){}
}
/* 该方法会有线程间通信问题
Iterator it = list.iterator();
while(it.hasNext())
{
String cmd = "···";
System.out.println(cmd);
try
{
Runtime.getRuntime().exec(cmd);
}
catch(IOException e){}
}
*/
}
}
class ParRun
{
public static void main(String[] args)
{
RunCmd r = new RunCmd();
Thread t0 = new Thread(r);
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
Thread t3 = new Thread(r);
Thread t4 = new Thread(r);
Thread t5 = new Thread(r);
t0.start();
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
现在暂未考虑同步问题,以后改进
参考的文章:
http://bbs.csdn.net/topics/390773319