Java Programming Lab
Session 8
By : Dr. Amar Arora
USAR, GGSIPU-EDC
Multithreading [[Link]
Multi processing
Multithreading
Operating System
Multithreading [[Link]
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use
a shared memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
process.
Java Multithreading is mostly used in games, animation, etc.
Java Thread State Diagram
Java Thread Class
Multithreading is a Java feature that allows concurrent execution of two or
more parts of a program for maximum utilization of CPU. Each part of such
program is called a thread. So, threads are light-weight processes within a
process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Multithreading Example by Extending Thread
Class
public class MyThread extends Thread {
public void run() {
[Link]("MyThread is running.");
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
[Link]();
[Link]("Main thread is running.");
}
}
Multithreading Example by Implementing
Runnable Interface
public class MyRunnable implements Runnable {
public void run() {
[Link]("MyRunnable is running.");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
[Link]();
[Link]("Main thread is running.");
}
}
Thread class important functions
start(): This method starts the thread, causing the run() method to be called
in a new thread of execution.
run(): This method is the entry point for the thread when it is started. It
contains the code that the thread executes in parallel with other threads.
sleep(): This method causes the thread to sleep for a specified amount of
time, allowing other threads to execute in the meantime. The thread calling
sleep() will pause its execution for the specified amount of time.
isAlive(): This method returns true if the thread is currently executing, and
false otherwise.
setPriority(): This method sets the priority of the thread, which can affect the
order in which threads are scheduled to execute by the JVM.
Program to Execute
15. Make 2 threads of same thread class printing the
odd numbers from 1 to 100 and demonstrate its
working using extend Thread class.
16. Convert program number 15 to implement
Runnable interface.