当我运行我的应用程序并扫描IP时,由于某种原因它会冻结。此外,我不确定Yum
方法在运行命令后是否退出,或者它是否永远存在。我的目标是制作像$ ./inLinuxRunMe &
这样的东西,它在后台运行,当工作完成后,就会自行杀死。
我不认为我的Yum
方法正在执行此操作,因为当我开始重载(例如播放视频等)时它会冻结。
public class MyShell
{
public static String whatIsMyIP = null;
public static void main(String args[])
{
t = new javax.swing.Timer(10000, new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
/* Scanner: if the ip change, show the new on too. */
whatIsMyIP = MyShell.Yum("ifconfig eth0 | grep inet").toLowerCase());
/* Some logical conditions ... such as if ran then dont run, run once etc..*/
bootMe();
}
});
t.start();
/* Launch: Main application server, runs forever as server */
// MyShell.Yum("java -cp myjar.jar launch.MainApplicationAsServer");
}
/* Boot loader */
public static void bootMe() throws IOException
{
MyShell.Yum("java -cp myjar.jar launch.MainApplicationAsServer");
}
/* Question: How to optimize it? So that,
it execute the shell command and quite*/
public static String Yum(String cmds)
{
String value = "";
try
{
String cmd[] = {"/bin/sh", "-c", cmds };
Process p=Runtime.getRuntime().exec(cmd);
BufferedReader reader=new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
value += line ;
line=reader.readLine();
}
p.waitFor();
} catch(IOException e1) {
} catch(InterruptedException e2) {
}
return value;
}
}
答案 0 :(得分:3)
在单独的线程中运行Yum()
方法。
答案 1 :(得分:2)
来自Java API:
Constructor Summary
Timer(int delay, ActionListener listener)
Creates a Timer that will notify its listeners every `delay` milliseconds.
所以它每10秒重复一次。你需要告诉它不要重复:
public void setRepeats(boolean flag)
If flag is false, instructs the Timer to send only one action event to its listeners.
Parameters:
flag - specify false to make the timer stop after sending its first action event
所以:
t = new javax.swing.Timer(10000, new ActionListener() {...});
t.setRepeats(false);
t.start();