Search code examples
javamultithreadingmethodsdelay

Delay a method on a new thread


I have 2 methods methodA, methodB. They run on different threads. I want methodB to run with a delay of 100 milliseconds after methodA have started, how do I do that?

the code

final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3);
executor.schedule(() -> highs(), 100, TimeUnit.MILLISECONDS);
new Thread(() -> highs()).start();
new Thread(() -> deleteRecords()).start();

I noticed that despise this, methodB always runs before methodA.


Solution

  • By having the ThreadPool execute one thread instantly and then schedule one 100ms later, you'll be able to get the effect you are looking for (having 1 thread run methodA and then another thread run methodB 100 milliseconds later). I wrote a small example to test this:

    public class Main {
    
        public static void main (String[] args) {
            ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3);
            executor.execute(() -> methodA());
            executor.schedule(() -> methodB(), 100, TimeUnit.MILLISECONDS);
        }
    
        public static void methodA(){
            System.out.println("A: " + System.currentTimeMillis());
        }
    
        public static void methodB(){
            System.out.println("B: " + System.currentTimeMillis());
        }
    }
    

    This program results in this output:

    A: 1575782281388
    B: 1575782281492