0% found this document useful (0 votes)
65 views

Java (Unit-4)

The document discusses threads in Java. It defines a thread as the path of execution in a program. The main thread is provided by the JVM to start program execution. Programs can have multiple concurrent threads that run independently with their own program counters, stacks, and variables. Threads can be created by extending the Thread class or implementing the Runnable interface. The lifecycle of a thread progresses from new to runnable to running to blocked or dead states. Common thread methods like start(), run(), sleep(), join(), etc. are also outlined.

Uploaded by

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

Java (Unit-4)

The document discusses threads in Java. It defines a thread as the path of execution in a program. The main thread is provided by the JVM to start program execution. Programs can have multiple concurrent threads that run independently with their own program counters, stacks, and variables. Threads can be created by extending the Thread class or implementing the Runnable interface. The lifecycle of a thread progresses from new to runnable to running to blocked or dead states. Common thread methods like start(), run(), sleep(), join(), etc. are also outlined.

Uploaded by

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

Thread

A thread in Java is the direction or path that is taken while a program is being executed.
Generally, all the programs have at least one thread, known as the main thread, that is
provided by the JVM or Java Virtual Machine at the starting of the program’s execution.
At this point, when the main thread is provided, the main() method is invoked by the
main thread.

A thread is an execution thread in a program. Multiple threads of execution can be run


concurrently by an application running on the Java Virtual Machine. The priority of each
thread varies. Higher priority threads are executed before lower priority threads.

Thread is critical in the program because it enables multiple operations to take place
within a single method. Each thread in the program often has its own program counter,
stack, and local variable.

Creating a Thread in Java


A thread in Java can be created in the following two ways:

1. Extending java.lang.Thread class

In this case, a thread is created by a new class that extends the Thread class, creating
an instance of that class. The run() method includes the functionality that is supposed to
be implemented by the Thread.

Below is an example to create a thread by extending java.lang.Thread class.

class Multi extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

Output

Here, start() is used to create a new thread and to make it runnable. The new thread
begins inside the void run() method.

2. Implementing Runnable interface

This is the easy method to create a thread among the two. In this case, a class iscreated
to implement the runnable interface and then the run() method.

The code for executing the Thread should always be written inside the run() method.
Here's a code to make you understand it.

class Multi3 implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}

Output

The start() method is used to call the void run() method. When start() is called, a new
stack is given to the thread, and run() is invoked to introduce a new thread in the
program.

Lifecycle of a Thread in Java

The Life Cycle of a Thread in Java refers to the state transformations of a thread that
begins with its birth and ends with its death. When a thread instance is generated and
executed by calling the start() method of the Thread class, the thread enters the
runnable state. When the sleep() or wait() methods of the Thread class are called, the
thread enters a non-runnable mode.

Thread returns from non-runnable state to runnable state and starts statement
execution. The thread dies when it exits the run() process. In Java, these thread state
transformations are referred to as the Thread life cycle.

There are basically 4 stages in the lifecycle of a thread, as given below:

1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead
 New State

As we use the Thread class to construct a thread entity, the thread is born and is
defined as being in the New state. That is, when a thread is created, it enters a new
state, but the start() method on the instance has not yet been invoked.

 Runnable State

A thread in the runnable state is prepared to execute the code. When a new thread's
start() function is called, it enters a runnable state.

In the runnable environment, the thread is ready for execution and is awaiting the
processor's availability (CPU time). That is, the thread has entered the queue (line) of
threads waiting for execution.

 Running State
Running implies that the processor (CPU) has assigned a time slot to the thread for
execution. When a thread from the runnable state is chosen for execution by the thread
scheduler, it joins the running state.

In the running state, the processor allots time to the thread for execution and runs its
run procedure. This is the state in which the thread directly executes its operations.
Only from the runnable state will a thread enter the running state.

 Blocked State

When the thread is alive, i.e., the thread class object persists, but it cannot be selected
for execution by the scheduler. It is now inactive.

 Dead State

When a thread's run() function ends the execution of sentences, it automatically dies or
enters the dead state. That is, when a thread exits the run() process, it is terminated or
killed. When the stop() function is invoked, a thread will also go dead.

Thread Methods

S.N. Modifier Method Description


and Type

1. void start() It is used to start the execution of


the thread.

2. void run() It is used to do an action for a


thread.

3. static void sleep() It sleeps a thread for the specified


amount of time.

4. static Thread currentThread() It returns a reference to the


currently executing thread object.

5. void join() It waits for a thread to die.

6. int getPriority() It returns the priority of the thread.

7. void setPriority() It changes the priority of the


thread.
8. String getName() It returns the name of the thread.

9. void setName() It changes the name of the thread.

10. long getId() It returns the id of the thread.

11. boolean isAlive() It tests if the thread is alive.

12. static void yield() It causes the currently executing


thread object to pause and allow
other threads to execute
temporarily.

13. void suspend() It is used to suspend the thread.

14. void resume() It is used to resume the suspended


thread.

15. void stop() It is used to stop the thread.

16. void destroy() It is used to destroy the thread


group and all of its subgroups.

17. void interrupt() It interrupts the thread.

18. boolean isinterrupted() It tests whether the thread has


been interrupted.

19. static boolean interrupted() It tests whether the current thread


has been interrupted.

20. static int activeCount() It returns the number of active


threads in the current thread's
thread group.

21. void checkAccess() It determines if the currently


running thread has permission to
modify the thread.

22. static void dumpStack() It is used to print a stack trace of


the current thread to the standard
error stream.

23. Thread.State getState() It is used to return the state of the


thread.
24. void notify() It is used to give the notification for
only one thread which is waiting for
a particular object.

Thread Priorities
The number of services assigned to a given thread is referred to as its priority. Any
thread generated in the JVM is given a priority. The priority scale runs from 1 to 10.

1 is known as the lowest priority.


5 is known as standard priority.
10 represents the highest level of priority.

The main thread's priority is set to 5 by default, and each child thread will have the
same priority as its parent thread. We have the ability to adjust the priority of any thread,
whether it is the main thread or a user-defined thread.
Multithreading in Java
In Java, multithreading is the method of running two or more threads at the same time
to maximize CPU utilization. As a result, it is often referred to as Concurrency in Java.
Each thread runs in parallel with the others.

S.NO Multi-tasking Multi-threading

Users are allowed to perform many Many threads are created from a process through
1. tasks by CPU. which computer power is increased.

The processes share separate


2. memory. Processes are allocated the same memory.

The multitasking component involves


3. multiprocessing. Component does not involve multiprocessing.

Processes don’t share the same


resources; each process is allocated
4. separate resources. Each process shares the same resources.

Multitasking is slow compared to


5. multithreading. While multithreading is faster.

Termination of a process takes more


6. time. Termination of thread takes less time.

Isolation and memory protection Isolation and memory protection does not exist in
7. exist in multitasking. multithreading.

It helps in developing efficient


8. programs. It helps in developing efficient operating systems.

Uncaught exception handler will be used to demonstrate the use of exception with
thread. It is a specific interface provided by Java to handle exception in the thread run
method.
There are two methods to create a thread:
1. Extend the thread Class (java.lang.thread)
2. Implement Runnable Interface (java.lang.thread)

1. Exception and Exception handling with threads


Here, a new thread is created in the class which is extending the thread
class in which run() method is overridden. This invokes the entry point of
the new thread created in the class which was extending the thread class.
Further, start() method is used to start and run the thread in the program.
// Java program to Use exceptions with
//thread
import java.io.*;
class c1 extends Thread {
public void run()
{

System.out.println("Thread is running");

for (int i = 0; i < 10; ++i) {


System.out.println("Thread
loop running " + i);

public static void main(String[] args)


{
try
{
c1 ob = new c1();
throw new RuntimeException();
}
catch (Exception e)
{
System.out.println("Another thread is not supported");

}}}

Output:
Another thread is not supported

2. Exception handling with sleep method():


sleep() method of thread class is used where there is a demand to sleep
the thread fora particular period of time for the proper workflow of the code
Syntax:
public static void sleep(long milliseconds) ; // generally used
public static void sleep(long milliseconds, int nanoseconds) ;
Name Action performed

milliseconds Duration of time to make a thread sleep

Additional duration of time to make thread sleep but


nanoseconds restricted to 999999

Return type: As seen in syntax itself, it does not return any value.
Exception:
1. IllegalArgumentException is thrown when the parametric value is
negative as it isbounded as discussed between [0 — +999999]

2. InterrupteException is thrown when a thread is interrupted with an


ongoing threadas discussed java supports the concepts of
multithreading.

// Java program to Use exceptions with thread


import java.io.*;
class C2 extendsThread
{
public void run()
{
System.out.println("Throwing in " +"MyThread");
throw new RuntimeException();
}
}
// Main driver method
public class Main {
public static void main(String[] args) {
C2 t = new
C2 ();
t.start();
Thread.sleep(2000); }
// catch block to handle the exception
catch (Exception x)
{
System.out.println("Exception" + x);
}
System.out.println("Completed");
} }
Output:
Throwing in MyThread
Exception in thread "Thread-0"
java.lang.RuntimeException at
testapp.MyThread.run(Main.java:19)
Completed

Synchronization in java
Synchronization is the capability to control the access of multiple threads to
any shared resource. In the Multithreading concept, multiple threads try to
access the shared resources at a time to produce inconsistent results. The
synchronization is necessary for reliable communication between threads.
 Synchronization helps in preventing thread interference.
 Synchronization helps to prevent concurrency problems.

Synchronization is classified into two types

1. Process Synchronization
2. Thread Synchronization

1) Process Synchronization:
The process is nothing but a program under execution. It runs independently isolated from
another process. The resources like memory and CPU time, etc. are allocated to the process by
the operation System.

2) Thread Synchronization:
Thread Synchronization helps only one thread to access the shared resources. It won’t allow the
accessing of shared resources at a time. It can be achieved in the following ways.
 Synchronized Method
 Synchronized block
 Static Synchronization

Package
Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces. Packages are used for:

Note: Sequence of the program must be package then import then class.
 Preventing naming conflicts.
For example
there can be two classes with name Employee in two packages,
college.staff.BBA.Employee and college.staff.BCA.Employee

 Making searching/locating and usage of classes, interfaces, enumerations and annotations


easier
 Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A
default member (without any access specifier ) is accessible by classes in the same
package only.
 Packages can be considered as data encapsulation (or data-hiding).

//adding class to a package


package mypack;
public class Bca
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

Accessing package from another package


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*
//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
3) Using packagename.classname
//save by A.java

package pack;
{
public class A
{
public void msg(){System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[])
{
A obj = new A();
obj.msg();
} }

3) Using fully qualified name


//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}

Example:
//Student.java
package student;
class Student
{
private int rollno;
private String name;
private String address;
public Student(int rno, String sname, String sadd}
{

rollno = rno;
name = sname;
address = sadd;
}
public void show()
{
System.out.println(“Roll No :: ” + rollno);
System.out.println(“Name :: ” + name);
System.out.println(“Address :: ” + address);
}
}
// Test.java

package student;
class Test extends Student

{
protected int marksSubjecti;
protected int marksSubject2;
protected int marksSubject3;
protected int marksSubject4;
public Test(int rno, String sname, String sadd,int mi, int m2, int m3, int m4)
{
super(rno,sname,sadd);
marksSubjecti = mi;
marksSubject2 = m2;
marksSubject3 = m3;
marksSubject4 = m4;
}
public void show()
{
super.show();
System.out.println(“Marks of Subject1 :: ” + marksSubject1);
System.out.println(“Marks of Subject2 :: ” + marksSubject2);
System.out.println(“Marks of Subject3 :: ” + marksSubject3);
System.out.println(“Marks of Subject4 :: ” + marksSubject4);
}
}
//Result.java

package student;
public class Result ex..tends Test
{
private int totalMarks;
private float percentage;
private char grade;
public Result(int rno, String sname, String sadd,int mi, int m2, int m3, int m4)
{
super(rno,sname,sadd,ml,m2,m3,m4);

totalMarks=marksSubject1+marksSubject2+marksSubject3+marksSubject4;
percentage = (totalMarks*100.00F/600.00F);
if (percentage >=50.00F)
grade=’D’;
else
if(percentage >=55.00F && percentage<=60.00F)
grade = ‘C’;
else
if (percentage >=6l.00F && percentage<=70.00F)
grade = ‘B’;
else
if(percentage >=7l.00F && percentage<=75.00F)
grade = ‘A’;
else
if (percentage >=76.00F && percentage<=85.00F)
grade = ‘H’;
else
grade = ‘S’;
}
public void show()
{
super.show();
System.out.println(“Total Marks :: ” + totalMarks);
System.out.println(“Percentage :: ” + percentage);
System.out.println(“Grade :: ” + grade);
}
}
//ImportPackageDemo.java
import student.Result;
public class ImportPackageDemo
{
public static void main(String ar[])
{
Result ob = new Result (1001, “Alice”, “New York”,135,130,132,138);
ob.show ();
}
}

Hiding classes:
When we import a package using asterisk (*),all public classes are imported. However, we may prefer to
“not import” certain classes i.e, we may like to hide these classes from accessing from outside of the
package. Such classes should be declared “not public”.

EX:

package p1;
public class X
{
Body of X
}

class Y
{
Body of Y
}

Hiding Classes in a Package


Here, the class y which is not declared public is hidden from out side of the package p1.
this class can be seen and used only by other classes in the same package note that a
java source file should contain only one public class and may include any number of non
public classes.

Now ,consider the following code ,which imports the package p1 that contains classes X and Y:

import p1.*;

X objectX;

Y objectY;

You might also like