【发布时间】:2018-06-13 17:45:23
【问题描述】:
我有一个 Java 程序,它接受两个数字作为用户输入并打印总和。
如果 30 秒后没有输入,则程序终止。
Java代码如下:
public class task {
static double i1;
static double i2;
static boolean breakOut = false;
public static void main(String[] args) throws IOException{
int x = 30; // time to wait, in seconds
while(true) {
boolean goodInput1 = false;
while(!goodInput1) {
BufferedReader in1 = new BufferedReader(new InputStreamReader(System.in));
Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
System.out.print("Current time: " + ft.format(date));
System.out.print(" Please enter the first number: ");
long startTime = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime) < x * 1000 && !in1.ready()) {}
try {
if (in1.ready()) {
i1 = Double.parseDouble(in1.readLine());
goodInput1 = true;
} else {
date = new Date();
System.out.print("\nTime now is: " + ft.format(date));
System.out.println(" You have not entered any number so exiting the program.");
breakOut = true;
break;
}
} catch (NumberFormatException e) {
System.out.println("You have entered bad data, please try again.");
continue;
}
}
if(breakOut) { break; }
boolean goodInput2 = false;
while(!goodInput2) {
BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
System.out.print("Current time: " + ft.format(date));
System.out.print(" Please enter the second number: ");
long startTime2 = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime2) < x * 1000 && !in2.ready()) {}
try {
if (in2.ready()) {
i2 = Double.parseDouble(in2.readLine());
goodInput2 = true;
} else {
date = new Date();
System.out.print("\nTime now is: " + ft.format(date));
System.out.println(" You have not entered any number, exiting the program.");
breakOut = true;
break;
}
} catch (NumberFormatException e) {
System.out.println("You have entered bad data, please try again.");
continue;
}
}
if(breakOut) { break; }
double sum = i1 + i2;
System.out.println("The sum is " + sum);
}
System.out.println("Program Terminated.");
}
}
我将程序保存为 Jar 可执行文件。
我编写了一个脚本来检查我的 Jar 进程当前是否正在运行,如果没有则启动该进程:
无论我尝试从多少个不同的 Bash 终端运行我的 Jar,此脚本都确保只有一个运行我的程序的 JVM 实例存在。 (假设我只使用我的脚本来运行进程)
最终目标是让任何连接到单个 JVM 的终端,都能够通过输入来重置 30 秒计时器。
我想更改脚本以实现此功能。 (更不用说对 Java 代码的更改了)
我的问题是:
鉴于 JVM 是从一个 Bash 终端启动的,我如何让另一个终端获得该特定 JVM 实例的句柄?
【问题讨论】:
-
java.net.ServerSocket/Socket
-
在 Unix 机器上,您可能可以让 JVM 以
/dev/[pt]tyXX直接打开其他终端,但您仍然需要告诉您的 JVM 它应该访问的终端,您需要使用 ServerSocket /Socket 或更高级的进程间通信形式。
标签: java bash jar terminal jvm