I have a problem synchronizing the critical area of a very simple program that takes a txt file containing ints, like: 0 1 2 3
reads the last int, close the file, then open the file again and write the following int. This has to be done several times. I want two (or more) threads to do that simultaneously. The run() method of my class (that extends Threads) is: public void run(){ for (int i=1; i<=10; i++){ read(); try { write(); } catch (IOException e){} } System.out.println(getName() + " has finished");
The read() and write() methods are both static.
How do I synchronize the access to the txt file? Thanks a million!!
You need to create a method which does the reaing / writing and put the "synchronized" tag in it's header. This way only one instance at a time is allowed. If a thread calls this method while another thread accesses it, the second thread waits until the first one exits from this method.