Java is an object-oriented programming language. Any java program is compiled and executed to get the desired output. It follows an architecture called JVM(Java virtual Machine).
Java code is compiled by java compiler(javac). Compiled code
is executed, and it gives the byte code. During this process JMM takes the control
over to the memory. It involves the threads.
Thread is a lightweight process. Multithreading deals with
multiple threads running at same time.
Why JMM?
JMM deals
with interactions between threads and memory. The memory can be classified into
two types.
·
Main memory – It’s the place where execution
takes place.
·
Working memory- It stores the details of
variables of the thread.
Features of JMM:
Volatile variables:
- Read and write operations on thread is visible for threads when it is declared as volatile.
Eg: private volatile boolean a = false;
Atomic functions:
- Volatile read and write operations are synchronized in atomic manner.
- Built in java package: “java.util.concurrent.atomic”
Synchronization:
When multiple
threads executed and a specific thread want to run in the execution block,it
needs to be synchronized.
Locks and monitor:
When threads are
running, one should use critical region. Another one should be wait for
critical region. This can be done by Locks and monitor.
Built in java package for implementing this concept:
java.util.concurrent.locks
Ordering:
This can
be done by two categories.
Happens-Before Relationship: It deals with visibility of
operations on memory.
Sequential consistency: The operations(read and write) is
consistent.
Let us create a simple thread sample in java.
- A class is created using Thread.
- Run() is a method in thread to execute the process.
- An object is created for the class.
- The thread is started by start() function.
Program:
import java.io.*;
import java.util.*;
// code for run
method
public void run()
{
System.out.println("It's the time to start the thread...");
}
public static void
main(String[] args)
{
sampleTh s1 =
new sampleTh();
// let us
start the thread
s1.start();
}
}
Here is the output.
C:\raji\blog>javac sampleTh.java
C:\raji\blog>java sampleTh
It's the time to start the thread...
This is a simple thread operation in java uses JMM.
No comments:
Post a Comment