0% found this document useful (0 votes)
2 views26 pages

Unit-4 Java

Unit 4 covers Threads and Packages in Java, explaining that a thread is a lightweight process allowing concurrent task execution without affecting the main program. It details the thread lifecycle, methods for creating threads, and the importance of thread priority. Additionally, it discusses Java packages, their organization, access methods, and advantages such as categorization and naming collision prevention.

Uploaded by

salonisingh58494
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)
2 views26 pages

Unit-4 Java

Unit 4 covers Threads and Packages in Java, explaining that a thread is a lightweight process allowing concurrent task execution without affecting the main program. It details the thread lifecycle, methods for creating threads, and the importance of thread priority. Additionally, it discusses Java packages, their organization, access methods, and advantages such as categorization and naming collision prevention.

Uploaded by

salonisingh58494
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/ 26

Unit 4

Threads and Packages


► 4.1 Thread
4.1.1 Introduction to Threads, Thread
Model 4.1.2 Priority of Threads
► 4.2 Package Naming, Type Imports 4.2.1
Package Access, Package Contents
4.2.2 Package Object and Specification
Thread
► A Thread is a very light-weighted process, or we can say the
smallest part of the process that allows a program to
operate more efficiently by running multiple tasks
simultaneously.

► In order to perform complicated tasks in the background, we


used the Thread concept in Java.

► All the tasks are executed without affecting the main


program. In a program or process, all the threads have their
own separate path for execution, so each thread of a
process is independent.

► Another benefit of using thread is that if a thread gets
an exception or an error at the time of its execution, it
doesn't affect the execution of the other threads.
► All the threads share a common memory and have their
own stack, local variables and program counter. When
multiple threads are executed in parallel at the same
time, this process is known as Multithreading.
► In a simple way, a Thread is a:
• Feature through which we can perform multiple
activities within a single process.
• Lightweight process.
• Series of executed statements.
• Nested sequence of method calls.
Thread Model

1) New (Ready to run)


A thread is in New when it gets CPU time.

2) Running
A thread is in a Running state when it is under execution.

3) Suspended
A thread is in the Suspended state when it is temporarily
inactive or under execution.

4) Blocked
A thread is in the Blocked state when it is waiting for
resources.
5) Terminated
A thread comes in this state when at any given time, it
halts its execution immediately
Creating Thread

► A thread is created either by "creating or implementing"


the Runnable Interface or by extending the Thread
class. These are the only two ways through which we
can create a thread.
Thread Class
► A Thread class has several methods and constructors
which allow us to perform various operations on a
thread. The Thread class extends the Object class. The
Object class implements the Runnable interface. The
thread class has the following constructors that are
used to perform various operations.
• Thread()
• Thread(Runnable, String name)
• Thread(Runnable target)
• Thread(ThreadGroup group, Runnable target, String name)
• Thread(ThreadGroup group, Runnable target) •
Thread(ThreadGroup group, String name)
• Thread(ThreadGroup group, Runnable target, String name,
long stackSize)
Runnable Interface(run() method)

► The Runnable interface is required to be implemented


by that class whose instances are intended to be
executed by a thread. The runnable interface gives us
the run() method to perform an action for the thread.
start() method

► The method is used for starting a thread that we have


newly created.
► It starts a new thread with a new callstack.

► After executing the start() method, the thread changes


the state from New to Runnable.
► It executes the run() method when the thread gets the
correct time to execute it.
Example
public class ThreadExample1 extends Thread {
// run() method to perform action for thread.
public void run()
{
int a= 10;
int b=12;
int result = a+b;
System.out.println("Thread started running..");
System.out.println("Sum of two numbers is: "+ result);
}
public static void main( String args[] )
{
// Creating instance of the class extend Thread class
ThreadExample1 t1 = new ThreadExample1();
//calling start method to execute the run() method of the Thread class
t1.start();
}
}

Priority of a Thread
► Each thread has a priority. Priorities are
represented by a number between 1 and
10.

► In most cases, the thread scheduler


schedules the threads according to their
priority
Setter & Getter Method of Thread Priority
► public final int getPriority():
The java.lang.Thread.getPriority() method returns the
priority of the given thread.
► public final void setPriority(int newPriority): The
java.lang.Thread.setPriority() method updates or
assign the priority of the thread to newPriority. The
method throws IllegalArgumentException if the value
newPriority goes out of the range, which is 1
(minimum) to 10 (maximum).
3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
► Default priority of a thread is 5 (NORM_PRIORITY).
We know that a thread with high priority will get
preference over lower priority threads when it
comes to the execution of threads. However,
there can be other scenarios where two threads
can have the same priority. All of the processing,
in order to look after the threads, is done by the
Java thread scheduler.
4.2 Package Naming, Type
Imports 4.2.1 Package Access,
Package Contents
4.2.2 Package Object and
Specification
► A java package is a group of similar types of classes, interfaces
and sub-packages.
► Package in java can be categorized in two form, built-in package
and user-defined package.
► There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Built-in Packages
1) java.lang: Contains language support classes(e.g classed which
defines primitive data types, math operations). This package is
automatically imported.
2) java.io: Contains classed for supporting input / output
operations.
3) java.util: Contains utility classes which implement data
structures like Linked List, Dictionary and support ; for Date /
Time operations.
4) java.applet: Contains classes for creating Applets. 5)
java.awt: Contain classes for implementing the components
for graphical user interfaces (like button , ;menus etc). 6)
java.net: Contain classes for supporting networking
operations.
Advantage of Java Package
1) Java package is used to categorize the classes
and interfaces so that they can be easily
maintained.
2) Java package provides access
protection. 3) Java package removes
naming collision.
Example
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Compile: javac -d . Simple.java
Run: java mypack.Simple
How to access package from another package?

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

► If you use package.* then all the classes and


interfaces of this package will be accessible but
not subpackages.

► The import keyword is used to make the classes


and interface of another package accessible to
the current package.
Example

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

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

►If
you import package.classname then only
declared class of this package will be
accessible.
Example

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

► If you use fully qualified name then only declared class


of this package will be accessible.
► Now there is no need to import.
► But you need to use fully qualified name every time
when you are accessing the class or interface.
Example

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

class B{
public static void main(String
args[]){ pack.A obj = new A();
obj.msg();
}
}
Subpackage in java
► Package inside the package is called the
subpackage.
► javac
mypack\testpack\MySubPackageProgram.java ► java
mypack.testpack.MySubPackageProgram

package mypack.testpack; class


MySubPackageProgram { public static void
main(String args []) { System.out.println("My sub
package program"); } }

You might also like