简体   繁体   English

Java中两个线程之间的时间延迟

[英]Time delay between two threads in Java

I have the following situation: 我有以下情况:

new Thread() {
    public void run() {
        method(object1);
    }
}.start();

// some code ... 

new Thread() {
    public void run() { 
        method(object2);
    }
}.start();

The used method is a map-drawing method. 使用的方法是地图绘制方法。 So basically, first I need to draw a map with object1 and then after some time eg 5 sec another map using object2 . 因此,基本上,我首先需要绘制一个带有object1的地图,然后在一段时间后(例如5秒钟)使用object2绘制另一个地图。

I tried to put Thread.sleep(5000) between two Thread s, also after and so on... But I couldn't make it work. 我试图将Thread.sleep(5000)放在两个Thread之间,等等。但是我无法使其正常工作。 Any suggestions? 有什么建议么?

In this case object 2 is displayed and the object 1 is not! 在这种情况下,将显示对象2,而不会显示对象1!
If I comment the second thread, the first object is drawn. 如果我注释第二个线程,则将绘制第一个对象。 Also if I comment the first thread the second object is drawn. 另外,如果我评论第一个线程,则绘制第二个对象。
The thing I need is to present object1 for 10 seconds and then to present object2. 我需要的是呈现对象1 10秒钟,然后呈现对象2。

Try making it easier: 尝试使其更容易:

method(object1);
Thread.sleep(5000);
method(object2);

There's no need to run threads if you need to wait for 5 seconds. 如果您需要等待5秒钟,则无需运行线程。

Alternatively, you can use java.util.Timer —but so far it seems your problem is not in the delay part. 或者,您可以使用java.util.Timer但是到目前为止,您的问题似乎不在延迟部分。

If you need to draw the map with object2 after object1, you should do 如果您需要在object1之后绘制带有object2的地图,则应该

new Thread() {
    public void run() {
        method(object1);
        method(object2);
    }
}.start();

I am not sure how long your method(object1) takes to run but if this takes more than 5 seconds and the thread comes back after the sleep, method(object2) will start and it is possible to the method(object2) will be done first if this take less time than method(object1). 我不确定您的method(object1)需要运行多长时间,但是如果这花费了5秒钟以上,并且线程在睡眠后返回,则method(object2)将启动,并且有可能method(object2)完成首先,如果此方法比method(object1)花费的时间少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM