简体   繁体   中英

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 .

I tried to put Thread.sleep(5000) between two Thread s, also after and so on... But I couldn't make it work. Any suggestions?

In this case object 2 is displayed and the object 1 is not!
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.

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.

Alternatively, you can use java.util.Timer —but so far it seems your problem is not in the delay part.

If you need to draw the map with object2 after object1, you should do

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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