If you want to synchronize processing between threads, you can use wait()
/notify()
, but if you're not sure about the order in which those "processings" will take place, I suggest you use a Semaphore
instead:
Semaphore sem = new Semaphore(0); // Initialize an empty Semaphore
new Thread(() -> { // This is thread A processing, that should run first
methodA(); // Run processing
sem.release(); // Indicate processing is finished
}).start();
new Thread(() -> { // This is thread B processing, that should run after methodA() has completed
sem.acquire(); // Blocks until release() is called by thread A
methodB(); // Run processing
}).start();
Original answer:
You wrote:
executor.schedule(() -> highs(), 100, TimeUnit.MILLISECONDS);
In 100ms highs()
will start.
new Thread(() -> highs()).start();
Another highs()
starts right now.
new Thread(() -> deleteRecords()).start();
deleteRecords()
starts right now.
So highs()
will be run twice: once with new Thread(() -> highs()).start()
and then later with executor.schedule()
.
Just comment out the new Thread(() -> highs()).start()
and the first executor schedule will trigger as you expected.
Note that thread execution does not necessarily happen in the order it was called, but it usually is the case though.