Java p13
Java p13
Java p13
1.1 Multithreading
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 :
We create a class that extends the java.lang.Thread class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object
of our new class and call start() method to start the execution of a thread. Start() invokes the
run() method on the Thread object
We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.
1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t
support multiple inheritance. But, if we implement the Runnable interface, our class can still
extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it provides
some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
3. Using runnable will give you an object that can be shared amongst multiple threads.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads.
It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is contextswitching
between the threads. There can be multiple processes inside the OS, and one process can have
multiple threads.
1.5 Java Thread class
Java provides Thread class to achieve thread programming. Thread
class provides constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
1.Implement a simple program which will just have a main thread. Implement all methods
in it like currentThread, sleep, and Setname
// Source Code
// Output
Fig: Output
// Output
Fig: Output
// Output
Fig: Output