In my project I have a game class which is called by a client class. At the moment the game class writes a path to a file and the client class will read from this file 开发者_开发百科and clear the contents. I am getting too many conflicts with access here so want to use another class as the method for storing the path data. I want to know, however, if there will still be a problem, or what the outcome will be if the game class tries to call the method in the storage class to write whilst the client class at the same instant calls the method in the storage class to read and clear.
Sounds like you need to think about threading and synchronization. I'd recommend reading "Java Concurrency in Practice".
In presence of multiple threads, your classes have to be thread safe. One way of achieving this is to make the concurrently accessed methods synchronized
.
Here is an example to get you started:
public class Test {
public static void main(String[] args) throws Exception {
new Thread() { public void run() { Test.method(); }}.start();
new Thread() { public void run() { Test.method(); }}.start();
}
public synchronized static void method() {
System.out.println("hello ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
System.out.println("world");
}
}
Without the synchronized
modifier, this program would have printed
hello
hello
world
world
With the synchronized
keyword, only one thread at a time can call method
, thus the program prints
hello
world
hello
world
I'm assuming your two classes are running in separate threads, so they might access the third class at the same time. The access to the resource they are reading and writing needs to be synchronized (mutexed). Java has the keyword "synchronized", which can be used in multiple ways to prevent concurrent modifications and such, see here and here for details
The theoretically correct answer is: "anything can happen".
The two calls can run one after the other or interleaved with each other, the results are unpredictable and potentially disastrous.
That's why Java offers you several ways of dealing with it.
The simplest (sounding) way is to write your methods threadsafe. In practice this usually means that you should only use local variables and must not modify the objects that are passed to you as parameters. (No side-effects.) Many methods automatically fall into this category, in which case you don't have to worry about concurrency.
If your method cannot be made threadsafe, you need to handle concurrent calls somehow.
synchronized
blocks are the most often used constructs but in some cases, avolatile
field or usingAtomic*
classes will suffice. But this subject is way too heavy to be covered in a single answer, so I suggest you read the concurrency tutorial.
精彩评论