0% found this document useful (0 votes)
22 views12 pages

CN Lab-3

The document discusses threads in Java, explaining that a thread is a sequential flow of execution within a program and that threads allow programs to perform multiple tasks simultaneously. It covers how to implement threading in Java by extending the Thread class or implementing the Runnable interface, and describes common thread methods like run(), start(), sleep(), and getPriority(). The challenges of multithreaded programming like thread interference are also addressed.

Uploaded by

adityadas.657
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views12 pages

CN Lab-3

The document discusses threads in Java, explaining that a thread is a sequential flow of execution within a program and that threads allow programs to perform multiple tasks simultaneously. It covers how to implement threading in Java by extending the Thread class or implementing the Runnable interface, and describes common thread methods like run(), start(), sleep(), and getPriority(). The challenges of multithreaded programming like thread interference are also addressed.

Uploaded by

adityadas.657
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 12

SOA, Bhubaneswar

Threads
 Threads: A thread in Java is the direction or path that is taken while a program is being
executed (In other word : Thread is lightweight sequential flow of controls within a
program).
 Generally, all the programs have at least one thread, known as the main thread, that is
provided by the JVM at the starting of the program’s execution; the main() method is
invoked by the main thread.
 Threads allows a program to operate more efficiently by doing multiple things at the
same time.
 Threads can be used to perform complicated tasks in the background without
interrupting the main program.
 Analogy: When we use Microsoft word, at the same time, one thread controls input, one
thread control grammar checking, one thread can be used for justification and so on.
09/03/2024
SOA, Bhubaneswar

Why Threads are Important


 Consider a client-server model: if a client is already connected with the server, how
other clients will get connect with the server?

Client Client
? S er ver t h read

Server Client Server Server thread Client


? Serve
r thre
ad
Client Client

09/03/2024
SOA, Bhubaneswar

Challenges for Implementing Threads


 The increased performance doesn’t come for free.
 There can be multiple issue as different thread share T1 T2
the same memory and resources.
• it’s entirely possible for one thread to stomp all over the
variables and data structures used by another thread.
• Generally, each thread must agree to use certain
resources only when it’s sure those resources can’t
change or that it has exclusive access to them. Program Variables: a, b,
Memory c…
• It’s also possible for two threads to be too careful, each
waiting for exclusive access to resources it will never get.
This can lead to deadlock condition. Program
• And thus with threads the overall complexity increases.

09/03/2024
SOA, Bhubaneswar

Implementing Threading in Java Public class HiThread extends Thread {


Public static void main (String [] args){
 There are two ways to implement threading in java HiThread thread = new HiThread();
thread.start();
 Extend java.lang.Thread class and override its run }
function. @Override
public void run (){
The task performed by thread
}}

Public class ThreadRun Implements Runnable {


Public static void main (String [] args){
ThreadRun thread = new ThreadRun();
 Implement java.lang.Runnable interface and pass thread.start();
the Runnable object to the Thread constructor }
@Override
public void run (){
The task performed by thread
}}

09/03/2024
SOA, Bhubaneswar

Thread Class:
 Thread class provide constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
 Constructor is a block of codes similar to the method. It is called when an instance of the
class is created.
 At the time of calling the constructor, memory for the object is allocated in the memory.
It is a special type of method that is used to initialize the object.
 Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)

09/03/2024
SOA, Bhubaneswar

Commonly used Methods


 public void run(): is used to perform action for a  public int getId(): returns the id of the thread.
thread.  public Thread.State getState(): returns the state of
 public void start(): starts the execution of the thread. the thread.
JVM calls the run() method on the thread.  public boolean isAlive(): tests if the thread is alive.
 public void sleep(long miliseconds): Causes the  public void yield(): causes the currently executing
currently executing thread to temporarily cease thread object to temporarily pause and allow other
execution for the specified number of milliseconds. threads to execute.
 public int getPriority(): returns the priority of the  public void suspend(): is used to suspend the
thread. thread.
 public int setPriority(int priority): changes the priority  public void resume(): is used to resume the
of the thread. suspended thread.
 public String getName(): returns the name of the  public void stop(): is used to stop the thread.
thread.  public boolean isDaemon(): tests if the thread is a
 public void setName(String name): changes the name daemon thread.
of the thread.  public void setDaemon(boolean b): marks the
 public Thread currentThread(): returns the reference of thread as daemon or user thread.
currently executing thread.  public void interrupt(): interrupts the thread.
09/03/2024
SOA, Bhubaneswar

Example: Extending Thread class (Subclassing)


class MyThread extends Thread{
public void run(){
System.out.println(“My first thread is running...");
}
Program
public static void main(String args[]){
MyThread t1=new MyThread ();
t1.start();
}
}

Output My first thread is running…

09/03/2024
SOA, Bhubaneswar

Example: Implementing Runnable Interface


class MyThread2 implements Runnable{
public void run(){
System.out.println(“My second thread is running...");
Program }

public static void main(String args[]){


MyThread2 t1=new MyThread2 ();
Thread t2 = new Thread(t1); // Using the constructor
t2.start();
}
}

Output My first thread is running…

09/03/2024
SOA, Bhubaneswar

Returning Information from Threads


 One of the hardest things for programmers accustomed to traditional, single-threaded
procedural models to grasp when moving to a multithreaded environment is how to
return information from a thread.
 Getting information out of a finished thread is one of the most commonly
misunderstood aspects of multithreaded programming.
 The run() method and the start() method don’t return any values.

09/03/2024
SOA, Bhubaneswar

Solution: Accessor method


 In Java, accessor methods return the value of
a private variable. public class MyThread implements Runnable {
private int value;
 This gives other classes access to that value public void run() {
stored in that variable without having direct value = 2;
access to the variable itself. }
 Accessor methods take no parameters and public int getValue() { // Accessor method
return value;
have a return type that matches the type of }
the variable they are accessing. }
 What If the main program use the thread value Public static void main (string [] args){
and the thread become dead? Mythread t1 = new MyThread ();
 What if the thread has not finished executing its int value = t1.getValue();
task and the accessor function is called?
 In both the cases we will get:
NullPointerException.

09/03/2024
SOA, Bhubaneswar

Solution: Callbacks
 The infinite loop that repeatedly polls each thread to see whether it’s finished can be
eliminated.
 The trick is that rather than having the main program repeatedly ask each thread
whether it’s finished, you let the thread tell the main program when it’s finished.
 It does this by invoking a method in the main class that started it.
 This is called a callback because the thread calls its creator back when it’s done.
 This way, the main program can go to sleep while waiting for the threads to finish and
not steal time from the running threads.
 A callback can be executed either synchronously or asynchronously. In the case of a
synchronous callback, one function is executed right after another. In the case of an
asynchronous callback, a function is executed after an undetermined period of time and
happens in no particular sequence with other functions
09/03/2024
SOA, Bhubaneswar

Solution: Callbacks
 Define the methods in an interface that we want to invoke after callback.
 Define a class that will implement the callback methods of the interface.
 Define a reference in other class to register the callback interface.
 Use that reference to invoke the callback method.
interface ResultCallback { // Define a callback interface
void onResult(String result); }
public class CallbackExample {
class WorkerThread extends Thread { // Thread class that performs public static void main(String[] args) { // Create a callback implementation
some work and invokes the callback ResultCallback callback = result -> { // Process the result in the main thread
private ResultCallback callback; System.out.println("Received result in the main thread: " + result); };
public WorkerThread(ResultCallback callback) { WorkerThread workerThread = new WorkerThread(callback); // start the worker
this.callback = callback; } thread with the callback
public void run() { // Simulate some work workerThread.start();
try { try { workerThread.join(); // Wait for the worker thread to complete
Thread.sleep(2000); // Sleep for 2 seconds to simulate work } catch (InterruptedException e) {
} catch (InterruptedException e) { e.printStackTrace(); }
e.printStackTrace(); } System.out.println("Main thread continues executing.");
String result = "Thread result data"; // // Perform the actual work }}
callback.onResult(result); // Invoke the callback with the result
}}

09/03/2024

You might also like