The Artima Developer Community
Sponsored Link

Java Answers Forum
problem synchronizing threads

1 reply on 1 page. Most recent reply: Feb 28, 2006 11:53 PM by Matthias Neumair

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
claudia dellington

Posts: 1
Nickname: franni
Registered: Feb, 2006

problem synchronizing threads Posted: Feb 28, 2006 1:27 PM
Reply to this message Reply
Advertisement
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!!


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: problem synchronizing threads Posted: Feb 28, 2006 11:53 PM
Reply to this message Reply
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.

Flat View: This topic has 1 reply on 1 page
Topic: how to read jsp tag in using xml Previous Topic   Next Topic Topic: JNI

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use