首先如果条件执行,然后调用一个方法,然后我停止控制 3 秒,然后如果条件再次执行一个方法并停止控制 3 秒,同样我执行 8 个如果条件。但我得到错误的输出。我的输出中发生的情况是,有时在控制停止方法完成之前调用方法。
这是我的编码和输出。给出一个解决方案
package com.example;
import java.util.Timer;
import java.util.TimerTask;
public class TimeBetween {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SecondClass obj = new SecondClass();
int a = 5;
int b = 3;
int c;
System.out.println("Timer Starts");
if (a == 5 && b == 3) {
c = a + b;
System.out.println("-----------Addition:" + c);
obj.secondClassMethod();
timeControlMethod();
}
if (a == 5 && b == 3) {
c = a - b;
System.out.println("-----------Subtraction:" + c);
obj.secondClassMethod();
timeControlMethod();
}
if (a == 5 && b == 3) {
c = a * b;
System.out.println("------------Multipication:" + c);
obj.secondClassMethod();
timeControlMethod();
}
if (a == 5 && b == 3) {
c = a % b;
System.out.println("-------------Modulo:" + c);
obj.secondClassMethod();
timeControlMethod();
}
if (a == 5 && b == 3) {
c = a + b;
System.out.println("************Addition:" + c);
obj.secondClassMethod();
timeControlMethod();
}
if (a == 5 && b == 3) {
c = a - b;
System.out.println("************Subtraction:" + c);
obj.secondClassMethod();
timeControlMethod();
}
if (a == 5 && b == 3) {
c = a * b;
System.out.println("***************Multipication:" + c);
obj.secondClassMethod();
timeControlMethod();
}
if (a == 5 && b == 3) {
c = a % b;
System.out.println("***************Modulo:" + c);
obj.secondClassMethod();
timeControlMethod();
}
System.out.println("Timer Ends");
}
private static void timeControlMethod() {
long getCurrentTimeInMilSec = System.currentTimeMillis();
long setEndTime = getCurrentTimeInMilSec + 3000l;
System.out.println("Time method waiting for 3 sec........");
while (setEndTime > System.currentTimeMillis()) {
}
}
}
class SecondClass {
public void secondClassMethod() {
System.err.println("Inside of SecondClass method");
}
}
输出:
Timer Starts
Inside of SecondClass method
-----------Addition:8
Time method waiting for 3 sec........
-----------Subtraction:2
Time method waiting for 3 sec........
Inside of SecondClass method
------------Multipication:15
Inside of SecondClass method
Time method waiting for 3 sec........
-------------Modulo:2
Time method waiting for 3 sec........
Inside of SecondClass method
************Addition:8
Time method waiting for 3 sec........
Inside of SecondClass method
Inside of SecondClass method************Subtraction:2
Time method waiting for 3 sec........
***************Multipication:15
Time method waiting for 3 sec........
Inside of SecondClass method
***************Modulo:2
Time method waiting for 3 sec........
Inside of SecondClass method
Timer Ends