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

unit 4 and 5

The document provides an overview of multithreading in Java, explaining its advantages over multiprocessing, the life cycle of a thread, and how to create threads using the Thread class and Runnable interface. It also covers Java packages, including their advantages, how to create and access them, and the concept of subpackages. Additionally, the document discusses method hiding in Java, comparing it with method overriding and highlighting the differences between static and instance methods.
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 views

unit 4 and 5

The document provides an overview of multithreading in Java, explaining its advantages over multiprocessing, the life cycle of a thread, and how to create threads using the Thread class and Runnable interface. It also covers Java packages, including their advantages, how to create and access them, and the concept of subpackages. Additionally, the document discusses method hiding in Java, comparing it with method overriding and highlighting the differences between static and instance methods.
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/ 19

Multithreading

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a


single thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:

 Process-based Multitasking (Multiprocessing)


 Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


 Each process has an address in memory. In other words, each process allocates a separate
memory area.
 A process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.
Life cycle of a Thread (Thread States)

In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Priorities in threads is a concept where each thread is having a priority which is represented
by numbers ranging from 1 to 10.

 The default priority is set to 5 as excepted.


 Minimum priority is set to 1.
 Maximum priority is set to 10.

Here 3 constants are defined in it namely as follows:

1. public static int NORM_PRIORITY


2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY

Java Threads | How to create a thread in Java

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

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.

Commonly used Constructors of Thread class:


 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().

1. ` to perform action for a thread.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:

 A new thread starts(with new callstack).


 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

FileName: Multi.java

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:

thread is running...

2) Java Thread Example by implementing Runnable interface

FileName: Multi3.java

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:

thread is running...

If you are not extending the Thread class, your class object would not be treated as a thread
object. So you need to explicitly create the Thread class object. We are passing the object of
your class that implements Runnable so that your class run() method may execute.

3) Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new threads using the constructors defined
above.
public class MyThread2 implements Runnable
{
public void run()
{
System.out.println("Now the thread is running ...");
}

// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();

// creating an object of the class Thread using Thread(Runnable r, String name)


Thread th1 = new Thread(r1, "My new thread");

// the start() method moves the thread to the active state


th1.start();

// getting the thread name by invoking the getName() method


String str = th1.getName();
System.out.println(str);
}
}
Java Package

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.

Here, we will have the detailed learning of creating and using user-defined packages.

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.

Simple example of java package


The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile java package


If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.

ow to access 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.*

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 of package that import the 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();
}
}

Output:Hello

2) Using packagename.classname

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

Example of package by import package.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();
}
}

Output:Hello

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.

It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Example of package by import 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();
}
}
Output:Hello

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
Note: Sequence of the program must be package then import then class.

Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.

Let's take an example, Sun Microsystem has definded a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and
ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java
package into subpackages such as lang, net, io etc. and put the Input/Output related classes in
io package, Server and ServerSocket classes in net packages and so on.

The standard of defining package is domain.company.package e.g. com.javatpoint.bean


or org.sssit.dao.

Example of Subpackage

package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}

To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output:Hello subpackage
Method Hiding in Java
In this section, we will discuss what is method hiding in Java, method hiding factors
(MHF), and the differences between method hiding and method overriding. Also,
implement the method hiding concept in a Java program.

To understand the method hiding concept in Java, first, we will understand the method
overriding. Because the method hiding concept is very similar to the method overriding.

What is method overriding?


Method overriding means subclass had defined an instance method with the same signature
and return type as the instance method in the superclass. In such a case, method of the
superclass is overridden (replaced) by the subclass.

Methods in Static Context

Static methods are bonded during compile time using types of reference variables not object.
We know that static methods are accessed by using the class name rather than an object. Note
that the static method can be overloaded, but cannot be overridden in Java.

What is method hiding?


Method hiding can be defined as, "if a subclass defines a static method with the same
signature as a static method in the super class, in such a case, the method in the subclass hides
the one in the superclass." The mechanism is known as method hiding. It happens because
static methods are resolved at compile time.

Method Hiding Factors (MHF)

The method hiding factors measure the invisibilities of methods in classes.

 An attribute is called visible if it can be accessed by another class or object. An attribute


should be hidden within a class. They can be kept from being accessed by other objects by
being declared private.
 Ideally, the method hiding factor must have a large value.
 The MHF can be calculated by using the following formula:

Example of Method Hiding in Java


Sample.java

//parent class
class Demo
{
public static void method1()
{
System.out.println("Method-1 of the Demo class is executed.");
}
public void method2()
{
System.out.println("Method-2 of the Demo class is executed.");
}
}
//child class
public class Sample extends Demo
{
public static void method1()
{
System.out.println("Method-1 of the Sample class is executed.");
}
public void method2()
{
System.out.println("Method-2 of the Sample class is executed.");
}
public static void main(String args[])
{
Demo d1 = new Demo();
//d2 is reference variable of class Demo that points to object of class Sample
Demo d2 = new Sample();
//method calling with reference (method hiding)
d1.method1();
d2.method1();
//method calling with object (method overriding)
d1.method2();
d2.method2();
}
}

Output:

Method-1 of the Demo class is executed.


Method-1 of the Demo class is executed.
Method-2 of the Demo class is executed.
Method-2 of the Sample class is executed.

We observe that the method of the superclass is hidden by the subclass.

Method Hiding Vs. Method Overriding


Hiding a static method of a superclass looks like overriding an instance method of a
superclass. The main difference can be seen at runtime in the following scenario.

 When we override an instance method, we get the benefit of run-time polymorphism.


 When we override a static method, we do not get the benefit of run-time polymorphism.

Method Hiding Method Overriding


Both methods must be static. Both methods must be non-static.
Method resolution takes care by the compiler Method resolution takes care by JVM based
based on the reference type. on runtime object.
It is considered as compile-time polymorphism It is considered as runtime polymorphism or
or static polymorphism or early binding. dynamic polymorphism or late binding.

Let's understand the method handing and overriding practically.

//parent class
class Demo
{
public void method1()
{
//statements
}
}
//child class
class Sample extends Demo
{
public void method1()
{
//statements
}
}

The above code snippet does not perform the method hiding because the methods of both the
classes are non-static, hence they perform method overriding.

In the above code snippet, to achieve the method hiding, we need to make the methods static.

//parent class
class Demo
{
public static void method1()
{
//statements
}
}
//child class
class Sample extends Demo
{
public static void method1()
{
//statements
}
}

The following table describes what happens when we define a method with the same
signature as in superclass.

Defining a Method with the Same Signature as a Superclass's Method


Superclass Instance Method Superclass Static Method
Subclass Instance Method Overrides the method Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides the method
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:

 It works at client side so less response time.


 Secured
 It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.

Drawback of Applet
 Plugin is required at client browser to execute applet.

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which
is the subclass of Component.

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1
life cycle methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object
that can be used for drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html
file and place the applet code in html file. Now click the html file.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
}

Displaying Graphics in Applet


java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with
the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with
the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is
used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle):
is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.

Example of Graphics in applet:


import java.applet.Applet;
import java.awt.*;

public class GraphicsDemo extends Applet{

public void paint(Graphics g){


g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);

}
}

myapplet.html

<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

Parameter in Applet

We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:

1. public String getParameter(String parameterName)


Example of using parameter in Applet:

import java.applet.Applet;
import java.awt.Graphics;

public class UseParam extends Applet{

public void paint(Graphics g){


String str=getParameter("msg");
g.drawString(str,50, 50);
}

myapplet.html

<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

You might also like