Reputation: 159
I want to update a file within thread. I have created a separate method for updateXML();
.
Thread1 and Thread2 both are calling the same method. I want only one method to call the method, the other shall wait.
Upvotes: 1
Views: 118
Reputation: 46
extract updateXML() method to separate class, not in the Runnable implemenation. Make this method a synchronized one. Something like this:
public class XmlUpdater {
public synchronized void updateXml() {
// do something. I imitate work :)
try {
System.out.println(Thread.currentThread().getName() + ". Updating XML");
Thread.sleep(10000);
System.out.println(Thread.currentThread().getName() + ". Updated successfully");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
now, create your threads or runnables, giving them (!!!important) the same instance of your xml updating class. Use it :) Example of main class:
public class ThreadTest {
static class TestRunnable implements Runnable {
private XmlUpdater updater;
TestRunnable(XmlUpdater updater) {
this.updater = updater;
}
public void run() {
updater.updateXml();
}
}
public static void main(String[] args) throws InterruptedException {
XmlUpdater updater = new XmlUpdater();
//NOTE the updater object is same for two runnables
Runnable runnable1 = new TestRunnable(updater);
Runnable runnable2 = new TestRunnable(updater);
Thread t1 = new Thread(runnable1);
Thread t2 = new Thread(runnable2);
System.out.println("Threads started");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Program ended");
}
}
My output is:
Threads started
Thread-0. Updating XML
Thread-0. Updated successfully
Thread-1. Updating XML
Thread-1. Updated successfully
Program ended
Upvotes: 0
Reputation: 7771
synchronized void updateXML() {
/* ... */
}
This, however, also locks other synchronized
methods of the class. You could use a lock object if necessary:
private final Object updateXmlLock = new Object();
void updateXML() {
synchronized(updateXmlLock) {
/* ... */
}
}
You can read more about intrinsic locks and synchronized methods in the Java tutorial.
Upvotes: 1