【发布时间】:2013-09-12 05:20:38
【问题描述】:
首先如果条件执行,然后调用一个方法,然后我停止控制 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
【问题讨论】:
-
我会建议你尝试利用Java线程等待和通知机制..玩线程睡眠方法不是一个好的解决方案
-
我尝试运行您的代码 4 次,每次我得到一致的输出,其中打印到控制台的文本顺序与源代码上的调用顺序一致。此外,我没有像您在上面的输出中那样得到任何缩进。你是如何运行你的程序的?
-
通过eclipse ide我运行程序