| Author |
About the Java thread synchronization discussed in Kathy and Bert's study guide
|
Helen Ma
Ranch Hand
Joined: Nov 01, 2011
Posts: 319
|
|
In the SCJP Sun Java 6 Certified programmer study guide written by Berts and Katy, on p 741, there is a sentence " a static method that access a non-static field (using an instance)"
In the following paragraph of the book, it talks about accessing a non-static filed of an object via a synchronzied static method and a synchronized non-static method by two threads. Since non-static and static synchronized methods do not block each other, the threads can modify the same non-static field concurrently. That will be messy.
But when I think of the sentence a static method that access a non-static field (using an instance)", a static method that access a non-static field won't even compile. If we create an instance inside the static method, that instance will be a local instance. On the previous page of this book, we don't need to synchronize any local instance because each thread that access the method has its own copy of the instance.
Can anyone explain this sentence " a static method that access a non-static field (using an instance)". For me, non-static field of an object cannot even be accessed in any static method.
Thanks.
|
 |
Alex Theedom
Greenhorn
Joined: Jan 18, 2012
Posts: 22
|
|
a static method that access a non-static field (using an instance)
This is how a static method can access a non-static field is via an instance. See the code below:
Here we have a static method (main()) in which an instance variable (instance) is used to access the non-static field myString.
|
Alex Theedom Senior Java Programmer.
|
 |
Helen Ma
Ranch Hand
Joined: Nov 01, 2011
Posts: 319
|
|
Thanks for your suggestion. I did the following and demo how a is changed by two threads (the main thread and the t thread).
In some applications, we don't want two threads to modify the same field.
public class SI {
int a =0;
public static void main (String... args) throws InterruptedException{
final SI i = new SI();
Thread t = new Thread(){
public void run() {
i.change();
}
};
t.start();
i.a = 3;
System.out.println("i "+ i.a);
}
public synchronized void change() {
a = 2;
try{
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e){
}
System.out.println(" change a into "+ a);
}
}
|
 |
 |
|
|
subject: About the Java thread synchronization discussed in Kathy and Bert's study guide
|
|
|