【发布时间】:2012-02-22 07:06:26
【问题描述】:
我愿意在我的应用程序中添加一个按钮,单击该按钮将重新启动应用程序。我搜索了谷歌,但发现除了 this one 之外没有任何帮助。但是这里遵循的过程违反了 Java 的 WORA 概念。
还有其他以 Java 为中心的方式来实现此功能吗?是否可以只分叉另一个副本然后退出?
提前致谢。感谢您的帮助。
@deporter 我已经尝试过您的解决方案,但它不起作用:(
@mKorbel 我根据您在so 中显示的概念编写了以下代码
JMenuItem jMenuItem = new JMenuItem("JYM");
jMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(true);
ScheduledFuture<?> future = executor.schedule(new Runnable() {
@Override
public void run() {
try {
Process p = Runtime.getRuntime().exec("cmd /c start java -jar D:\\MovieLibrary.jar");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}, 2, TimeUnit.SECONDS);
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});
还有:
ScheduledExecutorService schedulerExecutor = Executors.newScheduledThreadPool(2);
Callable<Process> callable = new Callable<Process>() {
@Override
public Process call() throws Exception {
Process p = Runtime.getRuntime().exec("cmd /c start java -jar D:\\MovieLibrary.jar");
return p;
}
};
FutureTask<Process> futureTask = new FutureTask<Process>(callable);
schedulerExecutor.submit(futureTask);
schedulerExecutor.shutdown();
try {
schedulerExecutor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.exit(0);
它的工作,但只有一次。如果我第一次启动应用程序并按下 JYM menuitem 然后它会关闭并在几秒钟后使用 cmd 打开一个新的 ui,但如果我按下该 JYM menuitem 应用程序完全终止,即它不再启动。
非常感谢您的帮助。
解决了。
【问题讨论】:
-
只是好奇,Java的WORA概念是什么?
-
@HarryJoy - en.wikipedia.org/wiki/Write_once,_run_anywhere
-
这个way是可以的,包括SingleInstance,App ---> SplashScreen --> App
-
@HarryJoy WODE 的妹妹 - write-once-debug-everywhere :)