2. Process
2
▰ A process has a self-contained execution environment. A process
generally has a complete, private set of basic run-time resource; in
particular, each process has its own memory space.
▰ Most implementations of the java virtual machine run as aa single
process.
3. Thread
▰ Threads are sometimes called lightweight processes.
Both processes and threads provide an execution
environment, but creating a new process.
▰ Threads exist within a process – every
process(application) has at least one thread.
▰ Threads share the process’s resources, including
memory and open files.
▰ Each thread is associated with an instance of the class
java.lang.Thread.
3
4. Threads and Processes
4
Process Process
Memory
Thread
Thread
Thread
Thread
Group
JVM(Java exe.)
Process
Operating System
Environment Variable
5. Multitasking and Multithreading
5
Multitasking refers to a computer’s ability to perform multiple jobs
concurrently. Multitasking means more than one programs are running
together on a single machine.
A thread is a single sequence of exception within a program.
Multithreading refers to multiple threads of control within a single
program. Each program can run multiple threads of control within it, e.g.,
Web Browser.
6. HelloWithoutThread
public class HelloWithoutThread{
String name= null;//Keep Thread Name
Public HelloWithoutThread(String threadName){//Constructor
name=threadName;
}
Public void run(){
for(int i=0; i<50; i++){
System.out.println(i + ”Hello James ”+name);
}
}
} 6
7. TestWithoutThread
Public static void main(String []args){
HelloWithoutThread t1 = new HelloWithoutThread(“Java”);
HelloWithoutThread t2 = new HelloWithoutThread(“Threads”);
t1.run();
t2.run();
}
7
9. Characteristics Of Threads
▰ A Thread can create another thread.
▰ Created threads will be equally powerful.
▰ Threads need same kind of resources to be executed.
▰ Threads work concurrently.
▰ If one thread dies, other will remain active in memory.
9
10. Creating Threads
▰ There are two ways to create a Thread object
▻ Inherit Thread class.
▻ Implement the Runnable.
▰ In both cases the run() method should be implemented.
10
11. HelloWithThread
Public class HelloWithThread extends Thread{
Private String name = null;
Public HelloWithThread(String threadName){
Name = threadName;
}
Public void run(){
for(int i=0; i<500; i++){
System.out.println(i + “Hello Thread “ + name);
}
}
}
11
12. TestWithThread
Public static void main(String []args){
HelloWithoutThread t1 = new HelloWithoutThread(“Java”);
HelloWithoutThread t2 = new HelloWithoutThread(“C++”);
t1.run();
t2.run();
for(int i=0; i<500; i++){
System.out.println(“Main Thread”);
}
}
12
13. TestWithThread Output
▰ 0 Hello Thread Java
▰ 1 Hello Thread Java
▰ 2 Hello Thread Java
▰ 0 Hello Thread C++
▰ 1 Hello Thread C++
▰ 1 Hello Thread main
▰ 2 Hello Thread main
▰ 3 Hello Thread main
▰ 3 Hello Thread Java
▰ 4 Hello Thread Java
▰ 2 Hello Thread C++
▰ 3 Hello Thread C++
▰ 4 Hello Thread main
▰ ……..
▰ 48 Hello Thread Java
▰ 49 Hello Thread Java
▰ 48 Hello Thread C++
13
14. Scheduling Threads
14
Newly created threads
Currently executed threads
Ready queue
• Waiting for I/O operation to be
completed
• Waiting to be notified
• Sleeping
• Waiting to enter a synchronized
section.
What happens when a program with
a ServerSocket calls accept() ?
I/O operation completes
Start()
15. Thread State Diagram
15
Alive
new ThreadExample();
New Thread
Running
While(…) {….}
Runnable
Blocked
Dead Thread
Thread.start(); Run() method returns
Object.wait()
Thread.sleep()
Blocking IO call
Waiting on a monitor
17. Child of other Class-Runnable Interface
If a class is child of another class and you want to make it Thread then use Runnable interface
since Java does not support multiple inheritance.
Public class HelloThread extends Hello implements Runnable{
public void run(){
System,out,println(“Hello From Thread!”);
}
Public static void main(String args[]){
HelloThread runThread = new HelloThread();
Thread th = new Thread(run Thread);
Th.start();
}
} 17
18. Thread Methods
▰ Void start()
▻ Creates a new thread and make it runnable.
▻ This method can be called only once.
▰ Void run()
▻ Thee new thread begins its inside this method.
▰ Void stop() (deprecated)
▻ The thread is begin terminated.
18
19. Thread Methods
▰ yield()
▻ Pause the currently executing thread object and
other thread of same priority to be executed.
▰ sleep(int m)/sleep(int m, int n)
▻ The thread is slept for m milliseconds and n
nanoseconds.
19
20. Multiple Threads in an Application
▰ Each thread has its private run-time stack.
▰ If two threads execute the same method, each will have
its own copy of the local variables the methods uses.
▰ However, all threads see the same dynamic memory
(heap).
▰ Two different threads can act on the same object and
same static fields concurrently. 20
21. Green Thread
▰ Native Thread model:
▻ The threads are scheduled by the OS.
▻ Maps a single Java thread to an OS thread.
▰ Green Thread model:
▻ The threads are scheduled by the Virtual Machine.
▻ Threads are invisible to the OS.
▻ Green threads emulate multithreaded environments without relying on any active OS
capabilities.
▻ They run code in user space that manages and schedules threads
▻ Green threads enables Java to work in environments that do not have native thread
support.
▻ OS doesn’t know anything about the threads used in the VM. It’s up to the VM to
handle all the details.
21
22. Scheduling
▰ Thread-scheduling is the mechanism used to determine
how runnable threads are allocated CPU time.
▰ A thread-scheduling mechanism is either preemptive or
non-preemptive.
22
23. Preemptive Scheduling
▰ Preemptive scheduling – the thread scheduler pre-
empts(pause) a running thread and executed other thread as
per schedule.
▰ Non-preemptive scheduling – the scheduler never interrupts a
running thread. Other thread will get chance only if current
thread dies.
▰ The non-preemptive scheduler relies on the running thread to
yield control of the CPU so that other threads may execute. 23
24. Starvation and Livelock
▰ A non-preemptive scheduler may cause starvation.
▰ Runnable threads which are in ready queue may have to
wait to be executed for a vary long time or forever.
▰ Sometimes, starvation is also called livelock.
24
25. Time-sliced Scheduling
▰ Time-sliced scheduling – the scheduler allocates a
period of time that each thread can use the CPU. When
that amount of time has elapsed, the scheduler pre-
empts the thread the thread and switches to other
thread.
▰ Non time-sliced scheduler – the scheduler does not use
elapsed time to determine when to pre-empts a thread,
It used other criteria such as priority or I/O status. 25
26. Java Scheduling
▰ Java-scheduler is preeemptive and based on priority of
threads.
▰ It uses fixed-priority scheduling.
▰ Threads are scheduled according to their priority with
respect to other threads in the ready queue.
26
27. Java Scheduling
▰ The highest priority runnable thread is always selected
for execution above lower priority threads.
▰ When multiple threads have equally high priority then
only one of them will be guaranteed to be executed.
▰ Java threads are guaranteed to be preemptive-but not
time sliced.
27
28. Thread Priority
▰ Every thread has a priority.
▰ When a thread is created, it inherits the priority of the
thread that created it.
▰ The priority values range from 1 to 10, in increasing
priority. That means 1 is lowest and 10 is highest.
28
29. Thread Priority
▰ The priority can be adjusted subsequently using the
setPriority(5) method.
▰ The priority of a thread may be obtained using getPriority().
▰ Priority constants are defined in Thread class:
▻ MIN_PRIORITY = 1
▻ MAX_PRIORITY = 10
▻ NORM_PRIORITY = 5
▰ Thread th = new Thread(“Raina”);
▻ Th.setPriority(4);
29
30. Some Notes
▰ Thread implantation in Java is actually based on
operating system support.
▰ Some Windows operating systems support only 7
priority levels, so mapped to the same operating
system level.
30
31. Dameon Threads
▰ Dameon threads are “background” threads, that provide
services to other threads, e.g., the garbage collection
thread.
▰ The Java VM will not exit if non-Daemon threads are
executing.
▰ Daemon threads will die when the Java VM exits.
▰ t.setDaemon(true) 31
32. Thread Group
▰ The ThreadGroup class is used to create
groups of similar threads.
32
34. ThreadInfo
Public static void info(String indent, ThreadGroup tg){
int threadCount = tg.activeCount(); //Get Active Thread Count
Thread[] threads = new Thread[threadedCount];
tg.enumerate(threads); //Get Active Threads
System.out.println(indent + “THREAD GROUP NAME: “ + tg.getName());
System.out.println(indent + “Is Daemon : “ + tg.isDaemon());
//Log Threads Details
for(int I = 0; I < threads.length(); i++){
log(indent + “t” , threads[i]);
}
int groupCount = tg.activeGroupCount(); //Get Active ThreadGroup Count
ThreadGroup[] groups = new ThreadGroup[groupCount];
tg.enumerate(groups); //Get ThreadGroups
for(int i = 0; i < groups.length; i++){
info(indent + “t”, groups[i]);
}}
34
35. ThreadInfo
Public static void main(String[] args) throws Exception{
Thread t = new Thread.currentThread(); //Get Current Thread
ThreadGroup tg = t.getThreadGroup();
While(tg.getParent() !=null){ //Get Root ThreadGRoup
Tg = tg.getParent();
}
HelloWithThread t1 = new HelloWithThread(“Traina”);
T1.setPriority(1);
HelloWithThread t2 = new HelloWithThread(“Yuvraj”);
T2.setPriority(1);
T1.start();
t2,.start();
Info(“”,tg);
}
35
36. Concurrency
▰ An object in a program can be changed by more than
one threads concurrently.
▰ Q. Is the order of changes that were performed on the
object important?
36
37. Race Condition
▰ When two threads are simultaneously modifying a
single object, is called race-condition.
▰ Both threads “race” to store their values in a single
object.
▰ The outcome of a program is affected by the order in
which the program’s threads are allocated CPU time.
37
38. Deposit in an Account
38
User 1 User 2
Account
Deposit in an Account
Balance = 1000
getBalance(); 1000
setBalance(2000)
getBalance(); 1000
setBalance(2000)
Balance = 2000
39. Synchronized access
39
User 1 User 2
Account
Deposit in an Account
Balance = 1000
getBalance(); 1000
setBalance(2000)
getBalance(); 2000
setBalance(3000)
Balance = 3000
40. Instance vs static attributes
40
instance
static
instance
static
Name = A
Address = Add11
1010
Name = B
Address = Add2
1011
+getName()
+getAddress()
$ getAveAge()
AVR_AGE = 60
Person
-name : String
-address : String
$ AVR_AGE :int = 60
+getName()
+getAddress()
$ getAveAge()
Class Methods
Attributes
1011
2B
p1
p2
1010
2B
Person p1,p2
P1 = new Person()
P2 = new Person()
P1.getName()
P2.getAvrAge()
Person.getAvrAge()
41. Account
Public class Account{
private int balance = 0;
public void deposit(String message. Int amount){
int bal = getBalance();
System.out.println(message + “Now Balance is “ +
getBalance());
}
public int getBalance(){
try{
thread.sleep(200); //simulate Database Operation
}catch(InterrruptedException e){
return balance;
}
41
43. RacingCondThread
Public class RacingCondThread extends Thread{
public static Account data = new Account();
String name = null;
public RacingCondThread(String name){
this.name = name;
}
public void run(){
for(int i=0; i<5; i++){
data.deposit(name,1000);
}
} 43
44. RacingCondThread
Public static void main(String[] args){
RacinfCondThread t1 = new RacingCondThread(“Raina”);
RacingCondThread t2 = new RacingCondThread(“Virat”);
t1.start();
t2.start();
}
44
45. Account - synchronized
Public class Account{
private int balance = 0;
public synchronized void deposit(String message, int amount){
int bal = getBalance() + amount;
setBalance(getBalance() + amount);
System.out.println(message + “Now Bal is” + bal);
}
//…..
} 45
46. Monitor Keys
46
Thread 1
Thread 2
Static Sync Methods
x
z
y
Instance Sync Methods
b
a
c
X() Class
Monitor
B()
y()
a() Object
Monitor
47. Synchronization types
▰ Method
Public synchronized void deposit(String message, int amount){……
▰ Block
Public void deposit(String message, int amount){
synchronized (this){
int bal = getBalance() + amount, setBalance(bal);
}
System.out.println(message + “Now Bal is” + bal);
} 47
48. Monitors
▰ Each object has a “monitor” that is a token used to
determine which application thread has control of a
particular object.
▰ Access to the object monitor is queued.
▰ There are two monitors:
▻ One for synchronized instance methods called
Object Monitor.
▻ Other for synchronized static methods called Class
Monitor. 48
49. Disclaimer
▰ This is an educational presentation to enhance the skill of
computer science students.
▰ This presentation is available for free to computer science
students.
▰ Some internet images from different URLs are used int his
presentation to simplify technical examples and correlate
examples with the real world.
▰ We are grateful to owners of these URLs and pictures. 49