Java Reference
In-Depth Information
As a last step, you have to create a new MsgThreadRunnable object and pass your
object to the Thread constructor. You then use the Thread object's start() method
to start your thread as follows:
MsgThreadRunnable msg1 = new MsgThreadRunnable ();
MsgThreadRunnable msg2 = new MsgThreadRunnable ();
Thread run1 = new Thread (msg1);
Thread run2 = new Thread (msg2);
run1.start();
run2.start();
// Perform some other logic, then stop the threads.
...
msg1.stopThread();
msg2.stopThread();
S YNCHRONIZATION
Java threads execute inside a single process (in this case the JVM) and, therefore,
share resources within the JVM. Threads in a process normally share the same class
instances and address space. Therefore, all object data members are shared between
the various threads.
Since Java threads share resources inside the process, the Java program itself has
to manage resource utilization conflicts. For example, it would ordinarily be inap-
propriate for a function to increment a variable while some other function resets
that variable to zero.
The solution for this problem is to synchronize your methods or objects. When
you synchronize a method, it waits for all other currently executing instances of this
object's method to complete. When you synchronize on an object, Java makes sure
that only one thread at a time modifies that object.
Java's synchronization coordinates access at the object level (either on a
java.lang.Object or on the java.lang.Class object in the case of class methods).
This means that two distinct object instances of the same class are not coordinated.
Static members can be synchronized, but they do not block access to synchronized
object instances. To protect a critical method against concurrent access, you can use
the synchronized keyword:
public class ErrorMsg {
public synchronized String getErrorMsg () {
}
}
Search WWH ::




Custom Search