这个程序主要是去监控,A,B,C存放的是其他批处理文件的title和path的!
大家赐教!
运行几天后会自动死掉!package com.delochi;import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;/**
 * @author vane
 * @监控系统中运行的批处理文件
 */
public class ThreadPool implements Runnable{


private static String path="tasklist /nh /fi \" imagename eq cmd.exe\" /v /fo table";//查询系统进程并且只显示图像名为cmd.exe的进程
private static int i = 0;

public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool();
while (true) {
try {
TimeUnit.SECONDS.sleep(10);
exec.execute(new ThreadPool());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} public void run() {
synchronized (this) {
i++;
System.out.println(getCurrentTime()+"扫描系统进程=====>>>>"+i+"次");
}
//boolean f=false;
int temp=i % 4;
switch (temp) {
case 0:
try {
System.out.println(getCurrentTime()+"没有需要启动的批处理!2分钟后在扫描");
TimeUnit.SECONDS.sleep(120);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
case 1:
A a=new A();
doExc(a.getAutoTitle(),a.getAutopath());
break;
case 2:
B b=new B();
doExc(b.getAutoTitle(),b.getAutopath());
break;
case 3:
C c=new C();
doExc(c.getAutoTitle(),c.getAutopath());
break;
}
}

/**
 * @param autoTitle 批处理的title
 * @param autoPath  批处理所在的路径
 */
public void doExc(String autoTitle,String autoPath){
boolean falg=isRun(autoTitle,path);
if(falg==true){
System.out.println(autoTitle+"===>>>监控已经启动!");
}else{
try {
System.out.println("正在启动......."+autoPath+"请稍等!");
TimeUnit.SECONDS.sleep(3);
runBat("cmd /c start "+autoPath);
} catch (InterruptedException e) {
System.out.println("启动:"+autoTitle+"出错!");
e.printStackTrace();
}
}
}

/**
 * @param title 批处理文件的title
 * @param str 系统中正在执行的批批处理
 * @return title是否在path中存在,也就是判断是否在系统进程存在
 */
public boolean isRun(String title,String str){
Pattern p=Pattern.compile(title);
Matcher m=p.matcher(runBat(str));
return m.find();
}

/**
 * @param path 批处理文件path
 * @return 批处理执行后的字符
 */
public String runBat(String path){
Process p;
try {
p = Runtime.getRuntime().exec(path);
InputStream inStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer = new StringBuffer();
for (;;)
{
int c = inStream.read();
if (c == -1)
break;
buffer.append((char) c);
}
String outputText = new String(buffer.toString().getBytes("ISO-8859-1"));
inStream.close();
return outputText;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

/**
 * @return 当前的系统时间
 */
public String getCurrentTime() {
java.util.Date d = new java.util.Date();
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return f.format(d);
}
}