How can i edit the following code so that in clearAndSave() method save() always runs after the clear() finishes its job.
clear() and save() method uses an object which creates new thread.
public class Test {
public void clearAndSave() {
clear();
save();
}
private void clear(){
// Deletes everything from DB.
}
private void save(){
// Adds new data into DB.
}
}
Without getting ride of the threads, it is not possible to achieve that effect unless you modify the threads code and use some mechanism to make the second thread wait until the first one is done. You can pass a reference of thread A to thread B and from B call
A.join, or you can instantiate aSemaphoreor aCountDownLatchand pass them to the threads, or crafting your own mechanism with wait-notify.This will, however, make your code more complicated. If you don’t need concurrency there, get rid of the threads.