Chapter 3 - Multithreading in Java
Chapter 3 - Multithreading in Java
# CoSc3052
Java
Multithreading
Mekonen M.
Computer Science Department
Hawassa University Daye campus, Daye
Chapter Three
Java Multithreading
Brainstorming question
1. What do you know about process and thread? What are some real-world examples of tasks
that would benefit from being divided into separate processes or threads?
2. What is the multitasking and how does it achieved?
3. What is multithread and how does it implement in java?
4. Explain the advantages of using multithreading in Java applications.
5. What are the key scheduling algorithms employed by thread schedulers, and what criteria
do they consider when making scheduling decisions?
Multiple threads
sharing a single
CPU
A process can communicate with other process A thread can communicate with other thread (of the same
by using inter-process communication. process) directly by using methods like wait(), notify(),
notifyAll().
Th
l runnable
un gna ll Waiting: Sometimes a thread transitions to the waiting state
rea Tas
si alA
dc k
n while the thread waits for another thread to perform a task. A
si g
om
Interval
expires
ait thread transitions back to the runnable state only when
await
ple
sleep
aw ck
tes
lo another thread signals waiting thread to continue.
Timed waiting: A runnable thread can enter the timed
timed waiting state for a specified interval of time. A thread in this
waiting terminated
waiting state transitions back to the runnable state when that time
interval expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state
when it completes its task or otherwise terminates.
// Start threads
thread1.start();
thread2.start();
thread3.start();
}
} Mekonen M. #CoSc3052 Multithreading 19
class PrintChar implements Runnable {
private char charToPrint;
private int times;
public PrintChar(char c, int t) {
charToPrint = c;
times = t;
}
public void run() {
for (int i = 0; i < times; i++) {
System.out.print(charToPrint);
}
}
}
class PrintNum implements Runnable{
private int lastNum;
public PrintNum(int n) {
lastNum = n;
}
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
}
}
}
To avoid contention, the thread with higher priority must periodically invoke the sleep or
yield method to give a thread with a lower or the same priority
a chance to run.
Starting a new thread for each task could limit throughput and cause poor performance.
A thread pool is ideal to manage the number of tasks executing concurrently.
A thread pool reuses previously created threads to execute current tasks and offers a solution
to the problem of thread cycle overhead and resource thrashing.
Java provides the Executor interface for executing tasks in a thread pool and the
ExecutorService interface for managing and controlling tasks.