作为一个初学者,我正在尝试编写类似的代码。当然,这是错误的方法,因为它根本不起作用。 我想做的是: 使用我在if循环内执行某操作时获得的结果,并在下次输入if时使用这些结果计算条件... 更确切地说,如果cond1 && cond2为TRUE,我想做同样的事情,但是即使情况发生(延迟1000)且值不低于前一个值,也不能尽早...
我不知道该如何编码,这是我第一次输入if和for其他... 你能帮我吗??? 非常感谢。
boolean cond_1 = a < 10;
boolean cond_2 = b < 15;
boolean cond_delay = (time_now - time_i_have_done_something) > 1000;
boolean cond_value = value_now > value_i_have_done_something;
if (cond_A1 == true && cond_A2 == true && cond_delay == true) {
do something;
long time_i_have_done_something = do_something.gettime();
double value_i_have_done_something = do_something.getvalue();
}
我要实现的逻辑示例:
if (cond_A1 == true) { // firt occurence at 7 h 30 min 00 sec 000 ms
time = gettime();
value = getvalue();
IOrder order = engine.submitOrder("EURUSD", instrument, orderCommand, 1);
}
if (cond_A1 == true) { // second occurence at 7 h 30 min 00 sec 190 ms
// do nothing because time between occurence#1 and occurence#2 < 1000 ms
}
if (cond_A1 == true) { // firt occurence at 7 h 30 min 01 sec 050 ms
// execute this because time between occurence#1 and occurence#3 > 1000 ms
time = gettime();
value = getvalue();
IOrder order = engine.submitOrder("EURUSD", instrument, orderCommand, 1);
}
答案 0 :(得分:2)
这将循环,并在调用操作doSomething()
之前,如果if将检查条件是否为真,并且自从上次执行操作以来已经过了1秒。它还将等待第一动作延迟1秒钟,因为第一次呼叫不会被视为特殊情况。可以通过这样声明启动来解决此问题:
long start = System.nanoTime() - timeBetween;
我输入了一个值为5的重复变量。当然可以删除它。
我选择不sleep()
线程,而选择yield()
,以使处理器能够执行其他任务,同时还可以忙于循环程序:
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
class StackOverflowTest {
public static void main(String [] args){
StackOverflowTest test = new StackOverflowTest();
test.notTooFast();
}
public void notTooFast(){
boolean condition1 = true;
long timeBetween = 1_000_000_000; // 1 second.
long start = System.nanoTime();
int repeat = 5; // run the loop only 5 times.
while (repeat > 0) { // or for an endless loop, use: while (true)
// has timeBetween passed since last time?
if (condition1 && (System.nanoTime() - start > timeBetween)) {
start = System.nanoTime(); // reset the time
doSomething(repeat--); // don't forget to decrease the counter.
} else {
Thread.currentThread().yield(); // hint to yield this threads current use of a processor.
}
}
}
// just print something for the sake of the example:
public void doSomething(int countdown){
System.out.println(LocalDateTime
.now()
.truncatedTo(ChronoUnit.MILLIS)
+ ": Doing something "
+ countdown);
}
}
它打印:
2020-07-15T13:30:34.409: Doing something 5
2020-07-15T13:30:35.350: Doing something 4
2020-07-15T13:30:36.350: Doing something 3
2020-07-15T13:30:37.349: Doing something 2
2020-07-15T13:30:38.350: Doing something 1
我想是那条线
doSomething(repeat--);
应该用这样的东西代替:
repeat--;
IOrder order = engine.submitOrder("EURUSD", instrument, orderCommand, 1);
您也可以使用{p>代替Thread.currentThread().yield();
try {
Thread.currentThread().sleep(1000); // 1 second.
} catch (InterruptedException ex) {
// handle whichever way
Thread.currentThread().interrupt(); // reset interrupt flag
}
这将使线程休眠1秒。