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

JAVA Unit 3

The document provides an overview of concurrency in Java, explaining concepts such as threads, Java API, packages, and multithreading. It details methods for creating threads, access modifiers, and the differences between classes and interfaces, including functional and marker interfaces. Additionally, it covers the life cycle of threads and the various states they can be in during execution.
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)
6 views

JAVA Unit 3

The document provides an overview of concurrency in Java, explaining concepts such as threads, Java API, packages, and multithreading. It details methods for creating threads, access modifiers, and the differences between classes and interfaces, including functional and marker interfaces. Additionally, it covers the life cycle of threads and the various states they can be in during execution.
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/ 14

UNIT – 3

1. What is concurrency?
 Concurrency is the ability to run several programs or several parts of a program
in parallel.
 The backbone of java concurrency is threads.
2. What is java API?
 Java API provides a large number of classes grouped into different packages
according to functionality.
 An API includes classes, interfaces, packages and also their methods, fields, and
constructors.
 All these built-in classes give benefits to the programmer
The most commonly used packages are:
 java.lang
 java.io
3. Define package. Mention its use.
A java package is a group of similar types of classes, interfaces and sub-packages.
Use: Packages are used for preventing naming conflicts.
4. Mention the ways of implementing multithreading in java.
Or
What are the ways to create threads in java?
 Extending Thread class: It can be created by extending the Thread class and
overriding its run().
 Implementing runnable interface: The easiest way to create a thread is to create
a class that implements the runnable interface.
5. Mention any four thread methods?
 start() – Starts the thread.
 getState() – It returns the state of the thread.
 getName() – It returns the name of the thread.
 getPriority() – It returns the priority of the thread.
 sleep() – Stop the thread for the specified time.
 Join() – Stop the current thread until the called thread gets terminated.
 isAlive() – Check if the thread is alive.
6. What are the different access modifiers in java?
 Private
 Default
 Protected
 public
7. Explain with an example the implementation of multithreading by extending ‘thread
class’.
8. What is functional interface & marker interface
A functional interface is nothing but an interface with only one method.
Example: public interface runnable
{
Public void run();
}
Marker interface is an interface with no methods declared.

Parameters Class Interface

Supported A class can have both an abstract Interface can have only abstract
Methods and concrete methods. methods.
Java 8 onwards, it can have both

Keyword A class is declared using class Interface is declared using interface


keyword. keyword.

Access A class can have any type of Interface can only have public
members like private, public. members.

Multiple Multiple Inheritance is not Interface supports Multiple Inheritance.


Inheritance supported.

Inheritance A class can be inherited using Interface can only be implemented


extends keyword. using implements keyword.

Constructor A class can have constructor Interface cannot have a constructor.


methods.

Supported final, non-final, static and non-static Only static and final variables are
Variables variables supported. permitted.

Implementa A class can implement an interface. Interface cannot implement an


tion interface, it can extend an interface.

Inheritance A class can inherit another class Interface can inherit only an interface.
using extends keyword and
implement an interface.
Interfaces:

 An interface which contains abstract methods and the data members (variables) are by
default static and final.
 The interface is used to achieve abstraction and multiple inheritance in java.
 Objects cannot be created for an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend interface or multiple interfaces.
 Since java 8, we can have default and static methods in an interface.

There are mainly three reasons to use interface.

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

Rules for defining an interface:

 All the variables are public, static and final by default.


 In any interface, the methods declared are public by default.
 Any non-abstract classes have to override all the methods declared in the super
interface.
 An interface can never extend any class.
 Nesting of interface is well supported in java.
 Methods in an interface cannot be declared as static and final.
 An interface can also be nested under a class.

Declaring/defining Interface:

 An interface is declared by using the interface keyword.


 It provides total abstraction; means all the methods in an interface are declared with
the empty body, and all the variables are public, static and final by default.
 General form/syntax:

interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Extending Interface

 An interface can extend another interface.


 When an interface wants to extend another interface, it uses the keyword extends.
 An interface cannot extend multiple interfaces.
 Example:
interface Parent
{
void parentMethod();
}
interface Child extends Parent
{
void childMethod();
}
class test implements Child{

public void childMethod() {


System.out.println("Child Interface method!!");
}
public void parentMethod() {
System.out.println("Parent Interface mehtod!");
}
}
public class run
{
public static void main(String[] args)
{
test obj = new test();
obj.childMethod();
obj.parentMethod();
}

}
OUTPUT: child interface method!!
Parent interface method!

Implementing Interface:

 When a class implements an interface, a class uses the implements keyword to


implement an interface.
 The implements keyword appears in the class declaration
 All the abstract methods from the interface must be override to subclass

When implementation interfaces, there are several rules −

 A class can implement more than one interface at a time.


 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, in a similar way as a class can extend
another class.
Example:
interface Bank
{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface
{
public static void main(String[] args)
{
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
Packages.
 A java package is a group of similar types of classes, interfaces and sub-packages.
 Package acts as “container” for classes.
 Use of package: to avoid name conflict, and to write better maintainable code
 Java packages classified into two types:
 Java API packages(built-in)
 User defined packages

Java API packages(built-in Packages)


 Java API provides a large number of classes grouped into different packages
according to functionality.
 included in the Java Development Environment.

Java.lang:
 Contains classes and interface required to write java programs.
 They are automatically imported
 Includes primitive types, strings, math functions, threads and exceptions
Object Class
 It is the super most class in java.
 Every class directly or indirectly inherits from object class.
 Object class is present in java.lang package.
 Every method of object class is non-static.
 Ex: hashcode(), notify(), notifyAll(), wait()
Java.util:
 Language utility classes such as vector, hash tables, random numbers
 Ex: ArrayList.class, map.class
Java.io:
 Provides for system input and output through data streams.
Java.awt:
 Contains all of the classes for creating user interfaces and for painting graphics and
images.
 EX: button.class
Java.net:
 Classes for networking.
 Include classes for communicating with local computers and with internet servers
Java.applet:
 Classes for creating and implementing applets

User defined packages


 User-defined packages are developed by users in order to group related classes,
interfaces and sub packages.

Creating packages:
 The package keyword is used to create a package in java.
 Declare the package at the beginning of a file.
 General form to create package:

package <package_name>;
public class <class_name>
{
body of class
}

Advantages of packages
 Maintenance of the application source code is easy
 It avoids name collision
 Java package provides access protection
 Easy accessibility
Accessing package:
 There are two ways to access the package from outside the package.
 Package name should be always written in lowercase

 Using Import statement


 import package.*;
 import package.classname;
 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");
}
}
//save by B.java
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");
}
}
//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


 A classname which is written with its package name is called as fully qualified
name
 Here no need of using import keyword.
 Syntax:
Domain.app.module.classname
Ex: com.gmail.inbox.demo
//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();
}
}
Adding a class to a package
 It is simple to add a class to an existing package.
Package p1;
Public class A
{
//body of A
}
 Here package p1 contains class A
 If we want to add another class B to the same package
 It can be done as below
Package p1;
Public class B
{
//body pf B
}
 Store this as B.java file under the directory p1.
 Now package p1 contains class A & B
Hiding Classes:
 If I use import packagename.*; all the classes of that package will be imported.
 If I not prefer few classes to be imported.
 Then I need to hide those classesfrom accessing outside of the package
 Such classes will not be declared as public
 Example:
Package p1
Public class X //public class , available outside
{
//body of X
}

Class y //not public, hidden class


{
//body of Y
}
Multithreaded programming
Thread:
 Thread is a lightweight process
 Allow multiple activities within a single process
 Is an independent part of same program which gets its own stack and CPU time for
execution.
 It is a series of executed statements
 Threads are used to achieve program level multitasking and concurrency
 Whenever JVM starts the execution it will create three threads
 Main thread
 Thread scheduler
 Garbage collector
 By default all the programs in java will be executed in main thread.
Multithreaded programming:
 A multithreaded program contains two or more parts that can run concurrently.
 Each part of such a program is called thread and each thread defines a separate path of
execution.
 Thus, multithreading is a specialized form of multitasking.

Creating threads
There are two ways to create a thread:
 Extending thread class
 Implementing Runnable interface

Extending Thread class:


 Create a class extending thread class
 Here we inherit run() method from thread class & then we override it in user defined
class(sub class)
 Create the object of subclass and using the subclass object call start() method
 To start run thread we use start() method of thread class implicitly
 Example:
public class MyThread extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String[] args)
{
MyThread obj = new MyThread();
obj.start();
}
}
Implementing Runnable Interface
 Create a class that implements the Runnable interface.
 To implement Runnable interface, a class need only implement a single method called
run( ).
 the thread can be run by passing an instance of the class to a Thread object's
constructor and then calling the thread's start() method.
 Example:
 Class BCA implements Runnable
{
Public void run()
{
System.out.println(“thread is running”);
}
Public static void main(String args[])
{
BCA b1 = new BCA();
Thread t1 = new thread(b1);
t1.start();
}
}

Stopping and blocking a thread

 Stop():
This method is used to stop a thread from running.
Stop() method will move the thread to dead state

Ex: Athread.stop();

 Sleep() //blocked for a specified time


 Suspend() //blocked until further orders
 Wait() //blocked until certain condition occurs

These methods cause a thread to go temporarily suspended or blocked from entering


into the runnable and running state
Life cycle of a thread
 A thread life cycle is divided into five different states,
 Thread may go through during in its lifetime.
 A thread can be in one of these five states.
 It can move from one state to another in different ways.

 New state
 Runnable state
 Running state
 Waiting or Blocked or sleep state
 Dead state

New State:
 When a new thread is created, it is in the new state.
 The thread will be in the new state until the start() method is called.

Runnable state:
 A thread enters the runnable state when the start() method is called.
 Now the thread is ready to run, but not yet running.
 Start(): this method is used to start the thread from new state to runnable state.
 Thread scheduler will decide which thread will move to the next state from the
runnable state
 A thread is considered as alive in the runnable state.
 A thread can return to the runnable state from sleep, wait, blocked or from running
state.
Running state:
 When thread enters the running state, the JVM start to execute the run() method.
 The most common change in the state of a thread is from runnable to running and again
back to runnable.
 Wait(): Whenever a thread is inactive thread will be in wait state for some time.
 When thread gets notify from thread scheduler it moves from wait to runnable state.
 Sometimes a thread needs to wait for a resource while running.
Dead state:
 A thread reaches the dead state because of the following reasons:
 When a thread has finished its job, then it exists or terminates normally.
 Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.
 A dead thread means the thread is no more in the system.

You might also like