Here's an example of threads. Threads can be created by extending the Thread class and overriding the run() method, or implementing a runnable and passing it to the Thread's constructor.
In this example, we implement the Runnable class.
Explicit synchronization/care should be taken to perform thread-unsafe operations. In this case, the access to the ThreadUnsafeCounter is explicity synchronized in CounterIncrementor. Try commenting out the synchronize block and see the results.
Checkout the code here.
In this example, we implement the Runnable class.
Explicit synchronization/care should be taken to perform thread-unsafe operations. In this case, the access to the ThreadUnsafeCounter is explicity synchronized in CounterIncrementor. Try commenting out the synchronize block and see the results.
Checkout the code here.
public class ThreadUnsafeCounter { | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
private int count = 0; | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
public int getCount() { | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
return count; | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
} | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// unsafe when multiple threads try to increment at the same time. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ALL callers need to use ensure that they do not call increment at the same | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// time. This may be done using explicit synchronize blocks. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
public void increment() { | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
count++; | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
} | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
}
|
No comments:
Post a Comment