SlideShare a Scribd company logo
Module 4 - Advanced features of Java
(Part 4)
1
Thread
• Threads are lightweight processes; they share the same address
space.
• Using thread we can do multiple activities within a single
process.
• E.g In a web browser
– we can scroll the page while it's downloading an applet or
image, play animation and sound concurrently,
– print a page in the background while you download a new
page
• All Java programs have at least one thread, known as the main
thread,
– which is created by the Java Virtual Machine (JVM) at
the program’s start, when the main() method is invoked with
the main thread. 2
Multithreaded Programming
• Java provides built-in support for multithreaded programming.
• A multithreaded program contains two or more parts that
can run concurrently (simultaneously).
• Each part of such a program is called a thread,
• Separate memory area is not allocated to threads.
• Threads are lightweight processes within a process.
• Multithreading is a specialized form of multitasking.
• Multithreading maximizes the utilization of CPU
3
Multitasking
4
• Multitasking- more than one task run concurrently.
• Two distinct types of multitasking:
– process based
• A process-based multitasking is the feature that allows your
computer to run two or more programs concurrently
• E,g. We can execute browser, paint software, calculator, notepad etc
at the same time.
– thread-based.
• The thread is the smallest unit of dispatchable code.
• A single program can perform two or more tasks
simultaneously.
• E.g. text editor can format text at the same time that it is printing, if
two actions are being performed by two separate threads.
Multithreading
• ADVANTAGE: Multithreading enables to
– Write very efficient programs that make maximum utilization of CPU
• because idle time can be kept to a minimum.
• This is especially important for the interactive, networked
environment, because idle time is common.
– Threads are independent.
• Applications: Games, animation etc.
5
Single threaded vs Multithreaded
• In a single-threaded environment, one program has to wait
for other program to finish —even though the CPU is sitting
idle most of the time.
• Multithreading helps to effectively make use of this idle
time.
6
The Java Thread Model
7
• Java uses threadsto enablethe entire environment to be
asynchronous.
– Asynchronous threading means, a thread once start
executing a task, can hold it in mid, save the current state
and start executing another task.
• This helps to increase efficiency by preventing the waste of
CPU cycles.
The Java Thread Model(contd.)
• Single-threaded systems use an approach called an event loop
with polling.
– In this model, a single thread of control runs in an infinite loop,
polling a single event queue to decide what to do next.
– In a singled-threaded environment, when a thread blocks (that is,
suspends execution) because it is waiting for some resource, the
entire program stops running.
• The benefit of Java’s multithreading is that the
main loop/polling mechanism is eliminated.
– One thread can pause without stopping other parts of your
program.
– When a thread blocks in a Java program, only the single thread that
is blocked pauses. All other threads continue to run.
8
The Java Thread Model (contd.)
Thread –
Threads exist in several states.
• A thread can be running.
• It can be ready to run(runnable) as soon as it gets CPU time.
• A running thread can be suspended(blocked), which
temporarily suspends its activity.
• A suspended thread can then be resumed(runnable), allowing it to
pick up where it left off.
• A thread can be blocked when waiting for a resource.
• At anytime, a thread can be terminated, which halts its
execution immediately.
– Once terminated, a thread cannot be resumed.
9
The Java Thread Model(contd.)
10
• Thread States
– New
– Runnable –ready to run
– Running
– Non-Runnable (Blocked)
– Terminated
The Java Thread Model(contd.)
• Thread life cycle
11
The Java Thread Model(contd.)
12
Thread Priorities
• Java assigns priority to each thread in the program.
– priority determines how that thread should be treated with
respect to the others.
• Thread priorities are integers
– that specify the relative priority of one thread to another
• A thread’s priority is used to decide when to switch from one
running thread to the next.
– Switching from one thread to another is called a context
switch
The Java Thread Model-Thread priorities(contd.)
13
• The rules that determine when a context switch takes place
are:
– A thread can voluntarily relinquish control. This is done by
explicitly yielding, sleeping, or blocking on pending I/O.
Here all other threads are examined, and the highest-priority
thread that is ready to run is given the CPU.
– A thread can be preempted by a higher-priority thread.
Here a lower-priority thread is simply preempted(forcely
suspended) by a higher-priority thread. i.e. As soon as a
higher-priority thread wants to run, it can run. This is called
preemptive multitasking.
• For operating systems such as Windows,
– threads of equal priority are time-sliced automatically in
round-robin fashion.
• For other types of operating systems,
– threads of equal priority must voluntarily yield control to
their peers.
– If they don’t, the other threads will not run.
14
The Java Thread Model-Thread priorities(contd.)
Synchronization
• Multithreading introduces an asynchronous behavior.
• But, when two or more threads need access to a shared resource,
they need some way to ensure that the resource will be used by only
one thread at a time. The process by which this is achieved is
called synchronization.
• Key to synchronization is the concept of the monitor (also called a
semaphore).
– Only one thread can own a monitor at a given time.
• Synchronization in Java can be achieved by
– Synchronized Methods
– The synchronized Statement
15
Messaging
16
• Java provides a clean, low-cost way for two or more threads to
talk to each other, via calls to predefined methods.
• Java’s messaging system
– allows a thread to enter a synchronized method on an
object,
– and then wait there until
• some other thread explicitly notifies it to come out.
Thread class methods
• Obtain a thread’s name.
getName
• Obtain a thread’s priority.
getPriority
• Determine if a thread is still running.
isAlive
• Wait for a thread to terminate.
join
• Entry point for the thread.
run
• Suspend a thread for a period of time.
sleep
• Start a thread by calling its run method
start
17
The Main Thread
18
• When a Java program starts up, one thread begins running
immediately.
– This is usuallycalled the main thread of
our program, because it is executed when our program begins.
• The main thread is important for two reasons:
1. It is the thread from which other “child” threads will be
spawned.
2. Often, it must be the last thread to finish the
execution
because it performs various shutdown actions.
The Main Thread(contd.)
19
• The main thread is created automatically when our program is
started.
• The Main thread can be controlled through a Thread object.
– To do so, we must obtain a reference to the thread by calling
the method currentThread( ), which is a public static
member of Thread class.
– Its general form is:
static Thread currentThread( )
• This method returns a reference to the thread in which it
is called.
• Once we have a reference to the main thread, we can
control it just like any other thread.
The Main Thread(contd.)
class CurrentThreadDemo
{
public static void main(String args[]) {
Thread t =
Thread.currentThread();
System.out.println("Current thread: " + t);
t.setName("My Thread");
System.out.println("After name change: " + t);
try { for(int n = 5; n > 0; n--)
{
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
} } }
Current thread: Thread[main,5,main]
After name change: Thread[My
Thread,5,main] 5
4
3
2
1
20
Working of the program
21
• In this program, a reference to the current thread (the main thread, in
this case) is obtained by calling currentThread( ), and this reference
is stored in the local variable t.
• Next, the program displays information about the thread.
• The program then calls setName( ) to change the internal name of
the thread. Information about the thread is then redisplayed.
• Next, a loop counts down from five, pausing one second(1000ms)
between each line.
– This pausing is accomplished by the sleep( ) method.
– The argument to sleep( ) specifies the delay period in
milliseconds.
Main thread(contd)
22
In the output ,Thread[main,5,main]
– Denotes that by default, the name of the main thread is
main.
– Its priority is 5, which is the default value,
– main is also the name of the group of threads to which this
thread belongs.
• A thread group is a data structure that controls the state of a
collection of threads as a whole.
Main thread(contd)
• If a thread calls sleep( ) method then execution of that thread
is suspended for the specified period of milliseconds.
• Its general form:
static void sleep(long milliseconds) throws InterruptedException
• The number of milliseconds
to
milliseconds. This method
suspend
may
is specified in
throw an
InterruptedException.
• The sleep( ) method has a second form,
static void sleep(long milliseconds, int nanoseconds) throws
InterruptedException
– This form is useful only in environments
that allow timing periods as short as nanoseconds.
23
Main thread(contd)
• We can set the name of a thread by using setName( ).
• We can obtain the name of a thread by calling getName( )
• These methods are members of the Thread class and are
declared as:
final void setName(String threadName)
final String getName( )
– Here, threadName specifies the name of the thread.
24
Creating a Thread
• Java defines two ways for creating thread:
– implement the Runnable interface.
– extend the Thread class.
25
1. Implementing Runnable
• The easiest way to create a thread is to create a class that
implements the Runnable interface.
• To implement Runnable, a class need only implement a single
method called run( ):
public void run( )
• Inside run( ), we will define the code that constitutes the new
thread.
• run( ) establishes the entry point for concurrent thread of execution
within our program. This thread will end when run( ) returns
26
Implementing Runnable(contd.)
1. Create a class that implements Runnable.
2. Instantiate an object of type Thread from within that class.
 Thread defines several constructors.
Thread(Runnable threadOb, String threadName)
o Here, threadOb is an instance of a class that implements
the Runnable interface. This defines where execution of
the thread will begin.
o The name of the new thread is specified by threadName.
1. After the new thread is created, it will start running when we
call its start( ) method, which is declared within Thread.
• start( ) executes a call to run( ).
• The start( ) method declaration is:
void start( )
27
32
class ThreadRunnableDemo implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
ThreadRunnableDemo trd = new ThreadRunnableDemo();
// Using the constructor Thread(Runnable r)
Thread t1 = new Thread(trd);
t1.start();
}
}
1. Implement the Runnable Interface.
2. Extending Thread
29
• Another way to create a thread is to
– Create a new class that extends Thread,
• 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.
33
2. Extend the Thread Class
class ThreadExtendsDemo extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
ThreadExtendsDemo t = new ThreadExtendsDemo();
t.start();
}
}
33
Example 2
class MultiThreadExtendsDemo extends Thread
{
public void run()
{
try
{
for(int i = 1; i <=5; i++)
{
System.out.println(i);
sleep(2000);
}
}catch(InterruptedException e){}
}
public static void main(String args[])
{
ThreadExtendsDemo t = new
ThreadExtendsDemo();
t.start();
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(i);
Thread.sleep(500);
}
} catch (InterruptedException e) {}
}
}
Questions
32
1. Write a program to print all the even numbers between 1 and
50 using a thread. Give 1 second delay between each print.
2. Write a Java program that implements a multi-threaded
program which has three threads. First thread generates a
random integer every 1 second. If the value is even, second
thread computes the square of the number and prints. If the
value is odd the third thread will print the value of cube of the
number

More Related Content

PPTX
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
PPTX
Object-Oriented-Prog_MultiThreading.pptx
PPTX
Multithreading in java
PPT
Session 7_MULTITHREADING in java example.ppt
PPTX
Multithreading in java
PPTX
multithreading,thread and processinjava-210302183809.pptx
PPT
9.multi-threading latest(MB).ppt .
PPTX
Multithreading
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
Object-Oriented-Prog_MultiThreading.pptx
Multithreading in java
Session 7_MULTITHREADING in java example.ppt
Multithreading in java
multithreading,thread and processinjava-210302183809.pptx
9.multi-threading latest(MB).ppt .
Multithreading

Similar to Module 4 - Part 4 - Multithreaded Programming.pptx (20)

PPTX
multithreading to be used in java with good programs.pptx
PPTX
Multithreading programming in java
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
PDF
java programming concept multithreading multitasking.pdf
PPTX
OOP with Java - Multithreading - Module-5.pptx
PPT
PDF
Java threads
PPT
multithreading, creating a thread and life cycle in java.ppt
PPTX
04 threads-pbl-2-slots
PPTX
04 threads-pbl-2-slots
PDF
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
PPTX
Thread priorities in java
PPTX
MSBTE Computer Engineering JPR java. multi. threading.pptx
PDF
Java Threads: Lightweight Processes
PPTX
Multi-threaded Programming in JAVA
PPTX
Multithreading in java
PPTX
Multithreading in java
PPTX
econtent thread in java.pptx
PDF
Multi t hreading_14_10
DOCX
Module - 5 merged.docx notes about engineering subjects java
multithreading to be used in java with good programs.pptx
Multithreading programming in java
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
java programming concept multithreading multitasking.pdf
OOP with Java - Multithreading - Module-5.pptx
Java threads
multithreading, creating a thread and life cycle in java.ppt
04 threads-pbl-2-slots
04 threads-pbl-2-slots
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
Thread priorities in java
MSBTE Computer Engineering JPR java. multi. threading.pptx
Java Threads: Lightweight Processes
Multi-threaded Programming in JAVA
Multithreading in java
Multithreading in java
econtent thread in java.pptx
Multi t hreading_14_10
Module - 5 merged.docx notes about engineering subjects java
Ad

Recently uploaded (20)

PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
Digital Logic Computer Design lecture notes
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
UNIT 4 Total Quality Management .pptx
DOCX
573137875-Attendance-Management-System-original
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
web development for engineering and engineering
PPTX
Welding lecture in detail for understanding
PPTX
additive manufacturing of ss316l using mig welding
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Digital Logic Computer Design lecture notes
CH1 Production IntroductoryConcepts.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
UNIT 4 Total Quality Management .pptx
573137875-Attendance-Management-System-original
Automation-in-Manufacturing-Chapter-Introduction.pdf
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
web development for engineering and engineering
Welding lecture in detail for understanding
additive manufacturing of ss316l using mig welding
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
OOP with Java - Java Introduction (Basics)
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Ad

Module 4 - Part 4 - Multithreaded Programming.pptx

  • 1. Module 4 - Advanced features of Java (Part 4) 1
  • 2. Thread • Threads are lightweight processes; they share the same address space. • Using thread we can do multiple activities within a single process. • E.g In a web browser – we can scroll the page while it's downloading an applet or image, play animation and sound concurrently, – print a page in the background while you download a new page • All Java programs have at least one thread, known as the main thread, – which is created by the Java Virtual Machine (JVM) at the program’s start, when the main() method is invoked with the main thread. 2
  • 3. Multithreaded Programming • Java provides built-in support for multithreaded programming. • A multithreaded program contains two or more parts that can run concurrently (simultaneously). • Each part of such a program is called a thread, • Separate memory area is not allocated to threads. • Threads are lightweight processes within a process. • Multithreading is a specialized form of multitasking. • Multithreading maximizes the utilization of CPU 3
  • 4. Multitasking 4 • Multitasking- more than one task run concurrently. • Two distinct types of multitasking: – process based • A process-based multitasking is the feature that allows your computer to run two or more programs concurrently • E,g. We can execute browser, paint software, calculator, notepad etc at the same time. – thread-based. • The thread is the smallest unit of dispatchable code. • A single program can perform two or more tasks simultaneously. • E.g. text editor can format text at the same time that it is printing, if two actions are being performed by two separate threads.
  • 5. Multithreading • ADVANTAGE: Multithreading enables to – Write very efficient programs that make maximum utilization of CPU • because idle time can be kept to a minimum. • This is especially important for the interactive, networked environment, because idle time is common. – Threads are independent. • Applications: Games, animation etc. 5
  • 6. Single threaded vs Multithreaded • In a single-threaded environment, one program has to wait for other program to finish —even though the CPU is sitting idle most of the time. • Multithreading helps to effectively make use of this idle time. 6
  • 7. The Java Thread Model 7 • Java uses threadsto enablethe entire environment to be asynchronous. – Asynchronous threading means, a thread once start executing a task, can hold it in mid, save the current state and start executing another task. • This helps to increase efficiency by preventing the waste of CPU cycles.
  • 8. The Java Thread Model(contd.) • Single-threaded systems use an approach called an event loop with polling. – In this model, a single thread of control runs in an infinite loop, polling a single event queue to decide what to do next. – In a singled-threaded environment, when a thread blocks (that is, suspends execution) because it is waiting for some resource, the entire program stops running. • The benefit of Java’s multithreading is that the main loop/polling mechanism is eliminated. – One thread can pause without stopping other parts of your program. – When a thread blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to run. 8
  • 9. The Java Thread Model (contd.) Thread – Threads exist in several states. • A thread can be running. • It can be ready to run(runnable) as soon as it gets CPU time. • A running thread can be suspended(blocked), which temporarily suspends its activity. • A suspended thread can then be resumed(runnable), allowing it to pick up where it left off. • A thread can be blocked when waiting for a resource. • At anytime, a thread can be terminated, which halts its execution immediately. – Once terminated, a thread cannot be resumed. 9
  • 10. The Java Thread Model(contd.) 10 • Thread States – New – Runnable –ready to run – Running – Non-Runnable (Blocked) – Terminated
  • 11. The Java Thread Model(contd.) • Thread life cycle 11
  • 12. The Java Thread Model(contd.) 12 Thread Priorities • Java assigns priority to each thread in the program. – priority determines how that thread should be treated with respect to the others. • Thread priorities are integers – that specify the relative priority of one thread to another • A thread’s priority is used to decide when to switch from one running thread to the next. – Switching from one thread to another is called a context switch
  • 13. The Java Thread Model-Thread priorities(contd.) 13 • The rules that determine when a context switch takes place are: – A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or blocking on pending I/O. Here all other threads are examined, and the highest-priority thread that is ready to run is given the CPU. – A thread can be preempted by a higher-priority thread. Here a lower-priority thread is simply preempted(forcely suspended) by a higher-priority thread. i.e. As soon as a higher-priority thread wants to run, it can run. This is called preemptive multitasking.
  • 14. • For operating systems such as Windows, – threads of equal priority are time-sliced automatically in round-robin fashion. • For other types of operating systems, – threads of equal priority must voluntarily yield control to their peers. – If they don’t, the other threads will not run. 14 The Java Thread Model-Thread priorities(contd.)
  • 15. Synchronization • Multithreading introduces an asynchronous behavior. • But, when two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. • Key to synchronization is the concept of the monitor (also called a semaphore). – Only one thread can own a monitor at a given time. • Synchronization in Java can be achieved by – Synchronized Methods – The synchronized Statement 15
  • 16. Messaging 16 • Java provides a clean, low-cost way for two or more threads to talk to each other, via calls to predefined methods. • Java’s messaging system – allows a thread to enter a synchronized method on an object, – and then wait there until • some other thread explicitly notifies it to come out.
  • 17. Thread class methods • Obtain a thread’s name. getName • Obtain a thread’s priority. getPriority • Determine if a thread is still running. isAlive • Wait for a thread to terminate. join • Entry point for the thread. run • Suspend a thread for a period of time. sleep • Start a thread by calling its run method start 17
  • 18. The Main Thread 18 • When a Java program starts up, one thread begins running immediately. – This is usuallycalled the main thread of our program, because it is executed when our program begins. • The main thread is important for two reasons: 1. It is the thread from which other “child” threads will be spawned. 2. Often, it must be the last thread to finish the execution because it performs various shutdown actions.
  • 19. The Main Thread(contd.) 19 • The main thread is created automatically when our program is started. • The Main thread can be controlled through a Thread object. – To do so, we must obtain a reference to the thread by calling the method currentThread( ), which is a public static member of Thread class. – Its general form is: static Thread currentThread( ) • This method returns a reference to the thread in which it is called. • Once we have a reference to the main thread, we can control it just like any other thread.
  • 20. The Main Thread(contd.) class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); t.setName("My Thread"); System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); } } } Current thread: Thread[main,5,main] After name change: Thread[My Thread,5,main] 5 4 3 2 1 20
  • 21. Working of the program 21 • In this program, a reference to the current thread (the main thread, in this case) is obtained by calling currentThread( ), and this reference is stored in the local variable t. • Next, the program displays information about the thread. • The program then calls setName( ) to change the internal name of the thread. Information about the thread is then redisplayed. • Next, a loop counts down from five, pausing one second(1000ms) between each line. – This pausing is accomplished by the sleep( ) method. – The argument to sleep( ) specifies the delay period in milliseconds.
  • 22. Main thread(contd) 22 In the output ,Thread[main,5,main] – Denotes that by default, the name of the main thread is main. – Its priority is 5, which is the default value, – main is also the name of the group of threads to which this thread belongs. • A thread group is a data structure that controls the state of a collection of threads as a whole.
  • 23. Main thread(contd) • If a thread calls sleep( ) method then execution of that thread is suspended for the specified period of milliseconds. • Its general form: static void sleep(long milliseconds) throws InterruptedException • The number of milliseconds to milliseconds. This method suspend may is specified in throw an InterruptedException. • The sleep( ) method has a second form, static void sleep(long milliseconds, int nanoseconds) throws InterruptedException – This form is useful only in environments that allow timing periods as short as nanoseconds. 23
  • 24. Main thread(contd) • We can set the name of a thread by using setName( ). • We can obtain the name of a thread by calling getName( ) • These methods are members of the Thread class and are declared as: final void setName(String threadName) final String getName( ) – Here, threadName specifies the name of the thread. 24
  • 25. Creating a Thread • Java defines two ways for creating thread: – implement the Runnable interface. – extend the Thread class. 25
  • 26. 1. Implementing Runnable • The easiest way to create a thread is to create a class that implements the Runnable interface. • To implement Runnable, a class need only implement a single method called run( ): public void run( ) • Inside run( ), we will define the code that constitutes the new thread. • run( ) establishes the entry point for concurrent thread of execution within our program. This thread will end when run( ) returns 26
  • 27. Implementing Runnable(contd.) 1. Create a class that implements Runnable. 2. Instantiate an object of type Thread from within that class.  Thread defines several constructors. Thread(Runnable threadOb, String threadName) o Here, threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begin. o The name of the new thread is specified by threadName. 1. After the new thread is created, it will start running when we call its start( ) method, which is declared within Thread. • start( ) executes a call to run( ). • The start( ) method declaration is: void start( ) 27
  • 28. 32 class ThreadRunnableDemo implements Runnable { public void run() { System.out.println("thread is running..."); } public static void main(String args[]) { ThreadRunnableDemo trd = new ThreadRunnableDemo(); // Using the constructor Thread(Runnable r) Thread t1 = new Thread(trd); t1.start(); } } 1. Implement the Runnable Interface.
  • 29. 2. Extending Thread 29 • Another way to create a thread is to – Create a new class that extends Thread, • 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.
  • 30. 33 2. Extend the Thread Class class ThreadExtendsDemo extends Thread { public void run() { System.out.println("thread is running..."); } public static void main(String args[]) { ThreadExtendsDemo t = new ThreadExtendsDemo(); t.start(); } }
  • 31. 33 Example 2 class MultiThreadExtendsDemo extends Thread { public void run() { try { for(int i = 1; i <=5; i++) { System.out.println(i); sleep(2000); } }catch(InterruptedException e){} } public static void main(String args[]) { ThreadExtendsDemo t = new ThreadExtendsDemo(); t.start(); try { for(int i = 5; i > 0; i--) { System.out.println(i); Thread.sleep(500); } } catch (InterruptedException e) {} } }
  • 32. Questions 32 1. Write a program to print all the even numbers between 1 and 50 using a thread. Give 1 second delay between each print. 2. Write a Java program that implements a multi-threaded program which has three threads. First thread generates a random integer every 1 second. If the value is even, second thread computes the square of the number and prints. If the value is odd the third thread will print the value of cube of the number