Chapter Multi 5
Chapter Multi 5
HOLETA CAMPUS
DEPARTMENT OF COMPUTER SCIENCE
Course Title: Java Programming
Course Code: CoSc3053
Credit Hrs: 3 ECTS: 5
Prerequisite: CoSc 2051- Object Oriented Programming
Instructor: Derartu.T (MSc)
08/12/2024 Java programming 1
Chapter 5: Multi-threading concept
5.1. Thread vs process
5.2. Multiple threads
5.2.1. Thread priorities
5.2.2. Thread synchronization
We know that every Java program has at least one thread called main thread.
When a program starts, main thread starts running immediately.
Apart from this main thread, we can also create our own threads in a program
that is called child thread.
Every child threads create from its main thread known as parent thread
There are two ways to create a new thread in Java:
By extending java.lang.Thread class
By implementing java.lang.Runnable interface
One way to create a thread is to create a new class that extends Thread,
and then to create an instance of that class.
The extending class must override the run() method, which is the entry
point for the new thread.
It must also call start() to begin execution of the new thread
Every Java thread has a thread priority that helps the operating system to
determine the order in which threads are scheduled priorities range between:
MIN_PRIORITY (a constant of 1)
NORM_PRIORITY (a constant of 5, default) and
MAX_PRIORITY (a constant of 10)
Each new thread inherits the priority of the thread that created it.
Note: In case two threads have the same priority, the JVM will execute
them in FIFO order.
Java's Thread class provides methods for checking the thread‟s priority and for
modifying it.
getPriority() method returns the integer that represents its priority.
setPriority(INT I) method takes integer between 1-10 to change thread's
priority.
If we pass a value outside the 1-10 range, the method will throw an error
08/12/2024 Java Programming lecture Note chapter five 20
Cont’d
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks.
You keep shared resources within this block
synchronized(objectidentifier){ // Access shared variables and other shared
resources; }