Thread is a lightweight process under execution. As java supports multithreading, thread synchronization is needed. It provides consistency. It also avoids thread interference.
Let us start the implementation.
Program implementation:
- Class: SharedResource, ThreadSynchronizationEg ,WorkerThread ( derived from Thread).
- Member variables: c( counting purpose), resrc ( object of SharedResource)
- Member functions:
- ‘increment()’ -used to increment the count(c) value.
- ‘getCount()’ -gets the count (c)value.
- Overridden ‘run()’ – runs the thread.
- ‘main()’
- It creates the object for SharedResource class.
- Threads are created and shared common resources.
- Thread process is started for both threads.
- They join the shared regions. Based on wait time, it is executed.
- Finally, the count value is printed.
Program:
class SharedResource {
private int c = 0;
// Thread safety
purpose, this method is used
public
synchronized void increment() {
c++;
System.out.println(Thread.currentThread().getName() + " count(incremented)
is: " + c);
}
public int
getCount() {
return c;
}
}
class WorkerThread extends Thread {
private
SharedResource resrc;
public
WorkerThread(SharedResource resrc) {
this.resrc =
resrc;
}
@Override
public void run()
{
for (int i =
0; i < 5; i++) {
resrc.increment();
try {
Thread.sleep(50);
} catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadSynchronizationEg {
public static void
main(String[] args) {
SharedResource
resrc = new SharedResource();
// Create
multiple threads sharing the same resource
Thread t1 =
new WorkerThread(resrc);
Thread t2 =
new WorkerThread(resrc);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch
(InterruptedException e) {
e.printStackTrace();
}
System.out.println("The final count is: " + resrc.getCount());
}
}
Output:
Compile and run the program to get the output.
C:\raji\blog>javac ThreadSynchronizationEg.java
C:\raji\blog>java ThreadSynchronizationEg
Thread-1 count(incremented) is: 1
Thread-0 count(incremented) is: 2
Thread-1 count(incremented) is: 3
Thread-0 count(incremented) is: 4
Thread-1 count(incremented) is: 5
Thread-0 count(incremented) is: 6
Thread-1 count(incremented) is: 7
Thread-0 count(incremented) is: 8
Thread-1 count(incremented) is: 9
Thread-0 count(incremented) is: 10
The final count is: 10
That’s the way of implementing thread synchronization in
java. Hope this code is easy to understand .Happy Coding!!!
No comments:
Post a Comment