Threads
Threads
Java Multithreading
1
Objectives ASET
2
Contents ASET
1. What is a Thread ?
2. Creating, Implementing and Extending a Thread
3. The life-cycle of a Thread
4. Interrupt a Thread
5. Thread synchronization
What is a Thread ? ASET
(Multiprocessing)
• Each process has an address in memory. In
other words, each process allocates a separate
memory area.
• A process is heavy weight.
• Cost of communication between the process is
high.
• Switching from one process to another requires
some time for saving and loading registers,
memory maps, updating lists, etc.
Thread-based Multitasking ASET
(Multithreading)
Newborn State:
When we want to create a thread object,
the thread is born then it is said to be Newborn
State.
At this State, we can do by using start() method.
Active: When a thread invokes the start()
method,
it moves from the new state to the active state.
The active state contains two states within it:
one is runnable, and the other is running.
Life cycle of a Thread ASET
16
Methods of Thread class: ASET
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM
calls the run() method on the thread.
• public void sleep(long miliseconds): Causes the
currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds.
• public void join(): waits for a thread to die.
• public void join(long miliseconds): waits for a thread to
die for the specified miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of
the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of
the thread.
Methods of Thread class: ASET
• public Thread currentThread(): returns the reference of currently
executing thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended
thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the thread has been
interrupted.
• public static boolean interrupted(): tests if the current thread has
Runnable interface: ASET
• The Runnable interface should be implemented by
any class whose instances are intended to be
executed by a thread. Runnable interface have only
one method named run().
• public void run(): is used to perform action for a
thread.
• Starting a thread:
• The start() method of Thread class is used to start a
newly created thread. It performs the following tasks:
• A new thread starts(with new callstack).
• The thread moves from New state to the Runnable
state.
• When the thread gets a chance to execute, its target
run() method will run.
thread is running...
Name) ASET
ASET
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
Race Conditions
Process A Process B Process A and B are sharing X at the same time. In this case,
output will not be correct. For ex:
X=10, after executing A , value of X should be 10+10=20. Process
Read X Read X B will read X as 20 and after increment the value of X should be
20+10=30.
X=X+10 X=X+10
But, in this case both process are executing at the same time.
X=10 Process A So, if Process A is executing so it will read X as 10 but if process
B starts at this time so it will also read X as 10. Now again
X=10 Process B process A execute and read X as 10 and increment it by 10. so
now X=20, Now process B executes and read X as 10 and again
increment it by 10. So, again X=20, which is wrong.
X=20 Process A This is example of race condition. It happens because
of thread interference or thread interleaving.
X=20 Process B
ASET
t1.start();
t2.start();
System.out.println(obj.x);
}} O/P: Inconsistent
results
ASET
Memory Inconsistency Error
In this case updates done by thread A in balance is not visible to thread B, So updated balance is 4000,
which is wrong. It should be 3000. It is called memory inconsistency error. It happens in case of parallel
execution. To avoid this, transaction B should not access balance when transaction A is executing.
ASET
Solution
Read X and X=X+10, should run in batch(one after another). It is called critical section.
X=10 is locked in this critical section. No another
process can read or modify X. Now next
Read X statement of this critical section will execute and
X=10 Process A x will become 20. Now all statements of critical
section has been executed, so, lock on A has been
Proces released.
X=20
sA
X=X+10
Process B
Now, Process B will read X=20 and it will lock X X=20 Process B
for its critical section, Now second statement of
Read X this critical section will execute and X=20+10=30. Proces
X=30
After this lock on X will be released. sB
https://www.youtube.com/watch?v=RH7G-N2pa8M&t=21s
X=X+10
Thread Synchronization
ASET
• Mutual Exclusive
– Synchronized method.
– Synchronized block.
• Cooperation (Inter-thread communication in
java)
Synchronization ASET
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(obj.count);
Will give you inconsistent results as threads are
} running at the same time. To solve this problem
} synchronized keyword should be used with the
name of function.
t1.start(); t2.start(); }
50
// Inter-thread Communication in Java
ASET