Pages

Saturday, 21 May 2022

Streams-Managing Input/Output Files In Java

Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow. Java I/O stream is the flow of data that you can either read from, or you can write to. It is used to perform read and write operations in file permanently. Java uses streams to perform these tasks. Java I/O stream is also called File Handling, or File I/O. It is available in java.io package and provides classes for system input and output through files, network streams, memory buffers, etc.

Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.

Some input-output stream will be initialized automatically by the JVM and these streams are available in System class as in, out, and err variable.

in reference refers to the default input device, i.e. keyboard.
out and err refers to the default output device, i.e. console.

Streams based on data are of two types namely:

1.Binary streams or Byte streams: These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images etc.

All byte stream classes are derived from base abstract classes called InputStream and OutputStream. 

2.Character Streams: These handle data in 16 bit Unicode. Using these you can read and write text data only. Character stream is used to read and write a single character of data.

All the character stream classes are derived from base abstract classes Reader and Writer.

The InputStream class of the java.io package is an abstract superclass that represents an input stream of bytes. Since InputStream is an abstract class, it is not useful by itself. However, its subclasses can be used to read data.

Working of Java OutputStream and InputStream

Diagram to illustrates all the input and output Streams (classes) in Java
 

Streams are the sequence of bits(data): 
There are two types of streams:
1.Input Streams (File.txt which is placed in harddisk to API interface(Program shell)
2.Output Streams  (API interface(Program shell) to File.txt which is placed in harddisk )
 
Input Streams:(FILE TO API)
Java application uses an input stream to read data from various input devices like keyboard, file, an array, peripheral device, network or socket etc.
The InputStream class of the java.io package is an abstract superclass that represents an input stream of bytes. Since InputStream is an abstract class, it is not useful by itself. However, its subclasses can be used to read data.

Subclasses of InputStream
In order to use the functionality of InputStream, we can use its subclasses. Some of them are:
  • FileInputStream
  • ByteArrayInputStream
  • ObjectInputStream
  • BufferedInputStream
  • DataInputStream

Creating an InputStream
In order to create an InputStream, we must import the java.io.InputStream package first. Once we import the package, here is how we can create the input stream.

// Creates an InputStream
InputStream object1 = new FileInputStream();
Here, we have created an input stream using FileInputStream. It is because InputStream is an abstract class. Hence we cannot create an object of InputStream.

Methods of InputStream (Read from a file into API )
The InputStream class provides different methods that are implemented by its subclasses. Here are some of the commonly used methods:
read() - reads one byte of data from the input stream
 
read(byte[] array) - reads bytes from the stream and stores in the specified array 
 
available() - returns the number of bytes available in the input stream
 
close() - closes the input stream
 
Ex:
 //import java.io.FileInputStream;
//import java.io.InputStream;
import java.io.*;
public class MainRead
{
  public static void main(String args[])
   {
    byte[] array = new byte[10];
    try
    {
    InputStream ip = new FileInputStream("input.txt");
    System.out.println("Available bytes in the file: " + ip.available());
    // Read byte from the input stream
    ip.read(array);
    System.out.println("Data read from the file: d:\\input.txt");
    // Convert byte array into string
    String data = new String(array);
    System.out.println(data);
    // Close the input stream
    ip.close();
    }
    catch (Exception e)
    {
    e.getStackTrace();
    }
   }
}
Output:

In the above example, we have created an input stream using the FileInputStream class. The input stream is linked with the file input.txt.
InputStream input = new FileInputStream("input.txt");
 
Note:
        To read data from the input.txt file, we have implemented the following two methods.
in.read(array); // to read data from the input stream
in.close();   // to close the input stream
 
Output Streams: (API TO FILE )
Java application uses an output stream to write the data to various output devices like monitor, file, an array, network, peripheral device or socket etc.
The OutputStream class of the java.io package is an abstract superclass that represents an output stream of bytes. Since OutputStream is an abstract class, it is not useful by itself. However, its subclasses can be used to write data.

Subclasses of OutputStream
In order to use the functionality of OutputStream, we can use its subclasses. 
Some of them are:
  • FileOutputStream
  • ByteArrayOutputStream
  • ObjectOutputStream
  • BufferedOutputStream
  • DataOutputStream


Create an Output Stream
In order to create an OutputStream, we must import the java.io.OutputStream package first.

Creating an Output Stream
OutputStream obj=new FileOutputStream();
Here, we have created an object of output stream using FileOutputStream. It is because OutputStream is an abstract class, so we cannot create an object of OutputStream.

Methods of OutputStream ( write from API into file )
write() - writes the specified byte to the output stream
 
write(byte[] array) - writes the bytes from the specified array to the output stream 
 
flush() - forces to write all data present in output stream to the destination
 
close() - closes the output stream

OutputStream Using FileOutputStream 
Ex:
import java.io.FileOutputStream;
import java.io.OutputStream;
public class MainW
{
  public static void main(String args[])
  {
    String data = "ram is a boy This is a line of text inside the file.";
    try
    {
    OutputStream out = new FileOutputStream("output.txt");
    // Converts the string into bytes
    byte[] dataBytes = data.getBytes();
    // Writes data to the output stream
    out.write(dataBytes);
    System.out.println("Data is written to the file.");
    // Closes the output stream
    out.close();
    }
    catch (Exception e)
    {
    e.getStackTrace();
    }
  }
}
Output:


Note:
        To write data to the output.txt file,we have implemented these methods
output.write(); // To write data to the file
output.close(); // To close the output stream

Character Stream classes
Character Stream Classes are used to read characters from the source and write characters to destination. There are two kinds of Character Stream classes - Reader classes and Writer classes. 
Reader Classes: These classes are subclasses of an abstract class, Reader and they are used to read characters from a source(file, memory or console).
Writer Classes: These classes are subclasses of an abstract class, Writer and they used to write characters to a destination(file, memory or console).

Reader:

Reader class and its subclasses are used to read characters from source.
Reader class is a base class of all the classes that are used to read characters from a file, memory or console. Reader is an abstract class and hence we can't instantiate it but we can use its subclasses for reading characters from the input stream.
 
Methods of Reader class.
Methods            Description
int read()         This method reads a characters from the input stream.
 
int read(char[] ch)       This method reads a chunk of characters from the input stream and store them in its char array, ch.
 
close()                This method closes this output stream and also frees any system resources connected with it.

Writer:
Writer class and its subclasses are used to write characters to a file, memory or console. Write class is a base class of all the classes that are used to write characters to a file, memory or console.Writer is an abstract class and hence we can't create its object but we can use its subclasses for writing characters to the output stream.


Methods of Writer class:
Methods of Writer class provide support for writing characters to the output stream. As this is an abstract class. Hence, some undefined abstract methods are defined in ths subclasses of OutputStream.

Methods                 Description
abstract void flush() This method flushes the output steam by forcing out buffered bytes to be written out.

void write(int c)         This method writes a characters(contained in an int) to the output stream. 

void write(char[] arr)      This method writes a whole char array(arr) to the output stream.

abstract void close() This method closes this output stream and also frees any resources connected with this output stream.

Example :Program to create a file, write data to the file, read and display the contents of the file. (OR)
Write a program to demonstrate Input / Output Streams in Java.
Note : You need to write two programs(need to create two files), One to input the data and the other to read the data.

File Name : FileCreation.java ( API TO FILE )
Note: The above file is used to input the data which in turn save the inputted data into a file named “rkdata.txt” )
import java.io.*;
public class FileCreation
{
  public static void main(String[] args)
  {   
    try
    {
    InputStreamReader is = new InputStreamReader(System.in);
    BufferedReader b=new BufferedReader(is);
    String st=null,ct="";
    char res='t';
    Writer w = new FileWriter("rkdata.txt");
    //String content = "This is to add a single line text...";
    while(res!='x')
    {
    st=b.readLine(); //Reads data in the stream character wise.
    res=st.charAt(0);
    if(res=='x')
        break;
    ct=ct+st+"\r\n"; //here \r\n combination is to produce a new line
    }
    w.write(ct);
    w.close();
    System.out.println("File Is Saved!!!");
    }
    catch (IOException e)
    {
    e.printStackTrace();
    }
  }
}
Output:
Command to compile: I:\>javac FileCreation.java 
Command to execute I:\>java FileCreation
ram is a boy 
x
File Is Saved!!!
Now check out  your file rkdata.txt file 

File Name : FileRead.java (file to API )
Note: The above file is used to read the data from the file named “vldata.txt” ) 
import java.io.*;
public class FileRead
{
   public static void main(String[] args)
    {
     BufferedReader br=null;
     try
     {
      String s;
      br=new BufferedReader(new FileReader("vldata.txt"));
      while ((s=br.readLine()) != null)
      {
       System.out.println(s);
      }
     }
     catch (IOException e)
      {
       e.printStackTrace();
      }
      finally
       {
        try
        {
        if (br!=null)
        br.close();
        }
        catch(IOException ex)
        {
        ex.printStackTrace();
        }
      }
    }
}
Output:

PACKAGES

A PACKAGE in Java is a collection of classes, sub-packages(package inside a package), and interfaces. It helps to organize classes into a folder structure and make it easy to locate and use them. More importantly, it helps to improve code reusability.

In java we have several built-in packages, for example when we need user input, we import a package as follows:
import java.util.Scanner; 
Here:
  • java is a top level package
  • util is a sub package of java
  • Scanner is a class which is present in the sub package util.
Advantages of using a package in Java
Reusability: While developing a project in java, we often feel that there are few things that we are writing again and again in our code. Using packages, you can create such things in form of classes inside a package and whenever you need to perform that same task, just import that package and use the class.

Better Organization: Again, in large java projects where we have several hundreds of classes, it is always required to group the similar types of classes in a meaningful package name so that you can organize your project better and when you need something you can quickly locate it and use it, which improves the efficiency.

Name Conflicts: We can define two classes with the same name in different packages so to avoid name collision, we can use packages

Types of packages in Java
1)User defined package: The package we create is called user-defined package.
2)Built-in package: The packages that are already defined,like java.io.*, java.lang.* etc are known as built-in packages.
Syntax to create a package:
package <nameOfPackage>; 
 
Command:package calculate;
 
How to Create a package?
  • Choose the name of the package
  • Include the package command as the first line of code in your Java Source File.
  • The Source file contains the classes, interfaces, etc you want to include in the package
  • Compile to create the Java packages.

Step 1) Type the following package program in notepad. 
package p1;
class Test
{
public void m1()
{
System.out.println("It is method m1 of the class Test");
}
public static void main(String args[])
{
Test t = new Test(); 
t.m1();
}
}

Step 2) In next step, save this file as Test.java

Step 3) In this step, we compile the file. 
I:\>javac Test.java
Note: Here Test.class will be created but no package is created.

Note:
We can create a package in two ways
Method 1 : Manually creating a directory for package.
Method 2 : Creating a directory for package using a command.

Method1
Manually creating a directory for package.
Step 4) create a folder named by package p1 
C:\Users\Student\Desktop\java prg\p1>dir
 Volume in drive C has no label.
 Volume Serial Number is B460-E456

Directory of C:\Users\Student\Desktop\java prg\p1>

24-05-2022  13:15    <DIR>          .
24-05-2022  13:15    <DIR>          ..
24-05-2022  13:16               517 Test.class
24-05-2022  12:28               202 Test.java
               2 File(s)            719 bytes
               2 Dir(s)  246,153,756,672 bytes free
 
Step 5) Compile the same file using the following code
C:\Users\Student\Desktop\java prg\p1>javac -d . Test.java
Here –d creates a directory and the "." operator represents the current working directory.

Step 6)Compile the same file using the following code
C:\Users\Student\Desktop\java prg\p1>javac -d .. Test.java
Here “..” indicates the parent directory. In our case file will be saved in parent directory which is C Drive

Step 7) To execute the code mention the fully qualified name of the class i.e. the package name followed by the sub-package name followed by the class name 
C:\Users\Student\Desktop\java prg\p1>java p1.Test
It is method m1 of the class Test

Example:
Procedure to create a package
//save the below program as Test.java 
package tstpkg;
public class Test
{
public static void main(String args[])
{
System.out.println("Testing a Package functionality");
}
}

Compile and create a package “tstpkg” in current directory as follows 
javac -d . Test.java

Run/execute Java package program
java tstpkg.Test

Output:
Testing a Package functionality

Example:
package com.rkblog;
public class Packrk
{
    public static void main(String[] args)
    {
    System.out.println(" It will dispaly package name");
    }
}     

Output:
ubuntu@ubuntu:~/Desktop/pk$ ls
Packrk.java
ubuntu@ubuntu:~/Desktop/pk$ javac -d . Packrk.java
ubuntu@ubuntu:~/Desktop/pk$ ls
com  Packrk.java
ubuntu@ubuntu:~/Desktop/pk$ cd com/
ubuntu@ubuntu:~/Desktop/pk/com$ ls
rkblog
ubuntu@ubuntu:~/Desktop/pk/com$ cd rkblog/
ubuntu@ubuntu:~/Desktop/pk/com/rkblog$ ls
Packrk.class
ubuntu@ubuntu:~/Desktop/pk/com/rkblog$ pwd
/home/ubuntu/Desktop/pk/com/rkblog
ubuntu@ubuntu:~/Desktop/pk/com/rkblog$ cd ..
ubuntu@ubuntu:~/Desktop/pk/com$ cd ..
ubuntu@ubuntu:~/Desktop/pk$ ls
com  Packrk.java
ubuntu@ubuntu:~/Desktop/pk$ javac -d . Packrk.java
ubuntu@ubuntu:~/Desktop/pk$ java com.rkblog.Packrk
 It will dispaly package name

Method 2 : Creating a directory for package using a command.
Step 4) To create a package using Method2, use the following command during compilation. javac –d . Test.java
Note: Here –d creates a directory and the "." operator represents the current working directory.

Step 5) When you execute the above command, it creates a package(directory) p1 in the current working directory, that is the location where we use above command. P1 directory contains the file named Test.class.

Example 1: 
Filename : Rk, Kk
 
Step 1: create a directory pk and then create a file Rk.java as shown 
ubuntu@ubuntu:~/Desktop/rkjava/$ mkdir pk
ubuntu@ubuntu:~/Desktop/rkjava/$ cd pk
ubuntu@ubuntu:~/Desktop/rkjava/pk$gedit Rk.java
ubuntu@ubuntu:~/Desktop/rkjava/pk$ ls
 lsRk.class  Rk.java
 
//Program :file name: Rk.java
package pk;
public class Rk
{
    public int add(int a,int b)
    {
        return a+b;
    }
    public int sub(int a,int b)
    {
        return a-b;
    }
    public int mul(int a,int b)
    {
        return a*b;
    }
    public int div(int a,int b)
    {
        return a/b;
    }
}

Step 2: create a file with Kk.java
import Pk.Rk;  // import <Package name>.<Class name>
class Kk
{
    public static void main(String []args)
    {
        Rk c=new Rk();
        int a=Integer.parseInt(args[0]);
        int b=Integer.parseInt(args[1]);
        int z=c.mul(a,b);
        int v=c.sub(a,b);
        System.out.println("Addition is:"+c.add(a,b));
        System.out.println("Division is:"+c.div(a,b));
        System.out.println("Multiplication is:"+z);
        System.out.println("Subtraction is:"+v);    
    }
}

Step 3: use the following command to run the package program 
ubuntu@ubuntu:~/Desktop$ mkdir pk
ubuntu@ubuntu:~/Desktop$ cd pk
ubuntu@ubuntu:~/Desktop/pk$ gedit Rk.java
ubuntu@ubuntu:~/Desktop/pk$ javac -d . Rk.java
ubuntu@ubuntu:~/Desktop/pk$ ls
pk  Rk.class  Rk.java
ubuntu@ubuntu:~/Desktop/pk$ cd ..
ubuntu@ubuntu:~/Desktop$ gedit Kk.java
ubuntu@ubuntu:~/Desktop$ javac -d . Kk.java
ubuntu@ubuntu:~/Desktop$ ls K*
Kk.class  Kk.java
ubuntu@ubuntu:~/Desktop$ java Kk 4 2
Addition is:6
Division is:2
Multiplication is:8
Subtraction is:2
                                            (OR)
Command to compile and to create a package Rk
ubuntu@ubuntu:~/Desktop/rkjava$ javac -d . Rk.java

Command to compile 
ubuntu@ubuntu:~/Desktop/rkjava$ javac  Kk.java

Command to execute 
ubuntu@ubuntu:~/Desktop/rkjava$ java  Kk 44 22

Output:
ubuntu@ubuntu:~/Desktop/rkjava$ javac -d . Rk.java
ubuntu@ubuntu:~/Desktop/rkjava$ javac  Kk.java
ubuntu@ubuntu:~/Desktop$ java Kk 4 2
Addition is:6
Division is:2
Multiplication is:8
Subtraction is:2

Example 2: 
Filename : Mensuration.java
package Calc;
public class Mensuration
{
public double volume(double l,double b,double h)
{
return l*b*h;
}
public double tsa(double l,double b,double h)
{
return 2*(l*b+b*h+l*h);
}
public double lsa(double l,double b,double h)
{
return 2*h*(l+b);
}
public double diag(double l,double b,double h)
{
return Math.pow(l*l+b*b+h*h,0.5);
}
public double peri(double l,double b,double h)
{
return 4*(l+b+h);
}
}
 
File Name : UseCalc.java 
import Calc.Mensuration;
import java.util.Scanner;
class UseCalc
{
public static void main(String x[])
{
double l,b,h;
Scanner s=new Scanner(System.in); 
Mensuration m=new Mensuration();
System.out.println("Enter Length, Breadth & Height:");
l=s.nextDouble();
b=s.nextDouble(); 
h=s.nextDouble();
System.out.println("Volume Of Cuboid: "+m.volume(l,b,h)); 
System.out.println("Total Surface Area :"+m.tsa(l,b,h)); 
System.out.println("Lateral Surface Area: "+m.lsa(l,b,h));
System.out.println("Length of diagonal of the cuboid: "+Math.round(m.diag(l,b,h))); 
System.out.println("Perimeter of Cuboid: "+m.peri(l,b,h));
}
}

Command to compile and to create a package Calc 
I:\>javac -d . Mensuration.java

Command to compile 
I:\>javac UseCalc.java 

Command to execute 
I:\>java UseCalc 

Output:
Enter Length, Breadth & Height: 
12
13
14
Volume Of Cuboid: 2184.0 
Total Surface Area :1012.0 
Lateral Surface Area: 700.0
Length of diagonal of the cuboid: 23 
Perimeter of Cuboid: 156.0
 
 

Friday, 20 May 2022

Threads

What is a Thread?
A thread is basically a lightweight and the smallest unit of process or lightweight sub-process, Threads share the common memory space. Java uses threads by using a "Thread Class". 
There are two types of threads, they are
user threads
daemon threads (daemon threads are used when we want to clean the application and are used in the background).
 
What are Advantages of single threads?
Reduces overhead in the application as single thread execute in the system. Also, it reduces the maintenance cost of the application.

Process Vs Thread:

PROCESS:                  
1.Program in execution is  called process
2.Process is a heavy wait.
3.Process takes more time context switching.
4.Process  takes more time in communication.
5.Each process has different address spaces.
6.Process are not dependent on each other.
7.It does not require synchronization.
8.Resource consumption is more in process.
9.Process requires more time creation.
10.Process takes more time in termination.

THREAD                
1.The sub part (small task)of process is called is thread.
2.Thread is a light wait.
3.Thread takes less time context switching.
4.Thread  takes less time in communication.
5.Thread share  has same address spaces.
6.Threads are  dependent on each other.
7.Threads may require synchronization.
8.Resource consumption is less in threads.
9.Thread requires less time creation.
10.Thread takes less time in termination.

Multitasking:
Performing multiple task at a single task, it increases the performance of CPU. There are two types of Multitasking:
1.Thread Based Multitasking (Multi Threading)
2.Process Based Multitasking (Multi Processing)


What is Multi-threading in Java?
Multi-threading in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU, so that the idle time of CPU can be kept to minimum. 
Multi-threaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other. 
Multiple threads don't allocate separate memory area, hence they save memory also, context switching between threads takes less time.

What is the purpose of Multithreading?
The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread. Threads are lightweight sub-processes, they share the common memory space. In Multithreaded environment, programs that are benefited from multithreading, utilize the maximum CPU time so that the idle time can be kept to minimum.

What are Advantages of multithreads?
The users are not blocked because threads are independent, and we can perform multiple operations at times.
As such the threads are independent, the other threads won't get affected if one thread meets an exception.

Java Thread Pool
Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times. In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider.

The Lifecycle of a thread:

 
 

There are various stages/states of life cycle of thread as shown in above diagram: 
1.New
2.Runnable 
3.Running 
4.Waiting 
5.Dead

New: A thread that has not yet started will be in this state. In this phase, the thread is created using class "Thread class". It remains in this state till the program starts the thread. It is also known as born thread. 

Runnable: A thread executing in the Java virtual machine is in this state. In this phase, the instance of the thread is invoked with a start() method. The thread control is given to scheduler to finish the execution. It depends on the scheduler, whether to run the thread.

Running: Once the thread starts executing, then the state is changed to "running" state. The scheduler selects one thread from the thread pool, and it starts executing in the application.

Waiting: A thread that is waiting indefinitely for another thread to perform a particular action is in this state. As there multiple threads are running in the application, there is a need for synchronization between threads. Hence, one thread has to wait, till the other thread gets executed. Therefore, this state is referred as waiting state.

Dead: This is the state when the thread is terminated. The thread is in running state and as soon as it completed processing it is in "dead state".

Note: A thread can be in only one state at a given point in time.

Multitasking vs Multithreading vs Multiprocessing vs parallel processing 

Multitasking: Ability to execute more than one task at the same time is known as multitasking. 

Multithreading: We already discussed about it. It is a process of executing multiple threads simultaneously. Multithreading is also known as Thread-based Multitasking.

Multiprocessing: It is same as multitasking, however in multiprocessing more than one CPUs are involved. On the other hand one CPU is involved in multitasking.
 
Parallel Processing: It refers to the utilization of multiple CPUs in a single computer system.

How to create a thread in Java?
In java we can create a thread in two ways. They are:
1)By extending Thread class.
2)By implementing Runnable interface.

Few Methods Of Thread Class
getName(): It is used for Obtaining a thread’s name
getPriority(): Obtain a thread’s priority 
isAlive(): Determine if a thread is still running 
join(): Wait for a thread to terminate
run(): Entry point for the thread
sleep(): suspend a thread for a period of time
start(): start a thread by calling its run() method

Method 1: creation of thread by extending Thread class
Ex1:
class ThreadDemo extends Thread
{
public void run()
{
System.out.println("Now the thread is in running state.");
}
public static void main(String args[])
{
ThreadDemo obj=new ThreadDemo(); 
obj.start();
}
}
Output:
C:\Users\Student\Desktop\java prg>javac ThreadDemo.java
C:\Users\Student\Desktop\java prg>java ThreadDemo
Now the thread is in running state.

Method 2: creation of thread by implementing Runnable interface 
import java.lang.*;
class UseRunnable implements Runnable
{
    public void run()
    {
    System.out.println("Thread created..using Runnable interface");
    }
    public static void main(String[] args)
    {
    UseRunnable e = new UseRunnable();
    Thread t1= new Thread(e);
    System.out.println("Is Thread alive:"+t1.isAlive());
    System.out.println("get the name of the Thread :"+t1.getName());
    t1.start();
    System.out.println("Is Thread alive:"+t1.isAlive());
    System.out.println("get the state of the Thread :"+t1.getState());
    System.out.println("get the Thread ID :"+t1.getId());
    System.out.println("Thread Priority :"+t1.getPriority());
    System.out.println("Current Thread :"+t1.currentThread());
    System.out.println("Is Thread alive:"+t1.isAlive());
    }
}
Output:
ubuntu@ubuntu:~$ javac UseRunnable.java
ubuntu@ubuntu:~$ java UseRunnable
Is Thread alive:false
get the name of the Thread :Thread-0
Is Thread alive:true
get the state of the Thread :RUNNABLE
get the Thread ID :8
Thread Priority :5
Thread created..using Runnable interface
Current Thread :Thread[main,5,main]
Is Thread alive:false
 
Method 2: creation of thread by implementing Runnable interface using WINDOWS
Ex2:
class UseRunnable implements Runnable
{
public void run()
{
System.out.println("Thread created..using Runnable interface");
}
public static void main(String[] args)
{
UseRunnable e = new UseRunnable(); 
Thread t1= new Thread(e);
t1.start(); 
System.out.println(t1.getState()); 
System.out.println(t1.isAlive()); 
System.out.println("Hi"); 
System.out.println(t1.getName()); 
System.out.println(t1.getPriority()); 
System.out.println(t1.currentThread()); 
System.out.println(t1.getId()); 
System.out.println(t1.getState()); 
System.out.println(t1.isAlive());
System.out.println("=====Created NewThread======"); 
Thread t2= new Thread(e);
t2.start(); 
System.out.println(t2.getState()); 
System.out.println(t2.isAlive()); 
System.out.println("Hi"); 
System.out.println(t2.getName()); 
System.out.println(t2.getPriority()); 
System.out.println(t2.currentThread()); 
System.out.println(t2.getId()); 
System.out.println(t2.getState()); 
System.out.println(t2.isAlive());
}
}

Output on windows:
C:\Users\Student\Desktop\java prg>javac UseRunnable.java
C:\Users\Student\Desktop\java prg>java UseRunnable
Thread created..using Runnable interface
RUNNABLE
false
Hi
Thread-0
5
Thread[main,5,main]
7
TERMINATED
false
=========Created New Thread===========
RUNNABLE
true
Thread created..using Runnable interface
Hi
Thread-1
5
Thread[main,5,main]
8
TERMINATED
false

Method 2: creation of thread by implementing Runnable interface using UBUNTU
Example:
class UseRunnable implements Runnable
{
    public void run()
    {
    System.out.println("Thread created..using Runnable interface");
    }
    public static void main(String[] args)
    {
    
    UseRunnable e = new UseRunnable();
    Thread t1= new Thread(e);
    System.out.println("isalive"+t1.isAlive());
    t1.start();
    System.out.println(t1.getState());
    System.out.println(t1.isAlive());
    System.out.println("Hi");
    System.out.println(t1.getName());
    System.out.println(t1.getPriority());
    System.out.println(t1.currentThread());
    System.out.println(t1.getId());
    System.out.println(t1.getState());
    System.out.println(t1.isAlive());
    System.out.println("=====Created NewThread======");
    Thread t2= new Thread(e);
    t2.start();
    System.out.println(t2.getState());
    System.out.println(t2.isAlive());
    System.out.println("Hi");
    System.out.println(t2.getName());
    System.out.println(t2.getPriority());
    System.out.println(t2.currentThread());
    System.out.println(t2.getId());
    System.out.println(t2.getState());
    System.out.println(t2.isAlive());
    System.out.println("=====Created NewThread======");
    Thread t3= new Thread(e);
    t3.start();
    System.out.println(t3.getState());
    System.out.println(t3.isAlive());
    System.out.println("Hi");
    System.out.println(t3.getName());
    System.out.println(t3.getPriority());
    System.out.println(t3.currentThread());
    System.out.println(t3.getId());
    System.out.println(t3.getState());
    System.out.println(t3.isAlive());
    }

Output on UBUNTU:
ubuntu@ubuntu:~/sudha$ javac UseRunnable.java
ubuntu@ubuntu:~/sudha$ java UseRunnable
isalivefalse
RUNNABLE
true
Hi
Thread-0
5
Thread[main,5,main]
8
RUNNABLE
true
=====Created NewThread======
RUNNABLE
true
Hi
Thread-1
5
Thread[main,5,main]
9
RUNNABLE
true
=====Created NewThread======
Thread created..using Runnable interface
Thread created..using Runnable interface
RUNNABLE
true
Hi
Thread-2
5
Thread[main,5,main]
10
RUNNABLE
true
Thread created..using Runnable interface

Thread Priorities
A thread priority decides how one thread is to be treated with respect to the other threads in an application. A thread priority is an integer number.

About Thread Priorities in Detail
  • Thread priorities are integer numbers.
  • Using thread priority, we can decide when we should switch from one thread in running state to another. This is the context switching process wherein we switch contexts of the threads.
  • Anytime a thread can voluntarily release its control over CPU. Then the thread with the highest priority can take over.
  • Similarly, a higher priority thread can pre-empt any other thread with lower priority.
  • Thread class provides a setPriority() method that is used to set the priority for the thread.
  • We can also use constants MIN_PRIORITY, MAX_PRIORITY, or NORM_PRIORITY in the place of integers.
Example:
public class PrTest extends Thread
{
    public void run()
    {
    System.out.println("Child Thread ");
    System.out.println("Child Thread Priority :"+Thread.currentThread().getPriority());
    }
    public static void main(String[] args)
    {
    System.out.println("Main Thread old Priority :"+Thread.currentThread().getPriority());
    Thread.currentThread().setPriority(3);
    System.out.println("Main Thread new Priority :"+Thread.currentThread().getPriority());
    PrTest t = new PrTest();
    t.start();
    }
}   
Note: instesd of setpriority(3) we can use 
MIN_PRIORITY will display 1
MAX_PRIORITY will display 10
NORM_PRIORITY will display 5
 
Output:
ubuntu@ubuntu:~$ javac PrTest.java
ubuntu@ubuntu:~$ java PrTest
Main Thread old Priority :5
Main Thread new Priority :3
Child Thread
Child Thread Priority :3

Different cases of executing Threads:The following are the 4 ways to execute 
1.Performing single task from single thread
2.Performing single task from multiple thread
3.Performing multiple task from single thread // it will not work
4.Performing multiple task from multiple thread  
 
1. Program to illustrate no 1.Performing single task from single thread
public class Test extends Thread
{
public void run()
{
System.out.println("Now the thread is in running state.");
}
public static void main(String args[])
{
Test t1=new Test(); 
t1.start();
}
}
Output:
vl@ubuntu:~$ javac Test.java
vl@ubuntu:~$ java Test
Now the thread is in running state.
 
2. Program to illustrate no 2.Performing single task from multiple thread
public class Test extends Thread
{
public void run()
{
System.out.println("Now the thread is in running state.");
}
public static void main(String args[])
{
Test t1=new Test(); 
t1.start();
Test t2=new Test(); 
t2.start();
Test t3=new Test(); 
t3.start();
  }
}
Output:
vl@ubuntu:~$ javac Test.java
vl@ubuntu:~$ java Test
Now the thread is in running state.
Now the thread is in running state.
Now the thread is in running state.

3. Program to illustrate no 3.Performing multiple task from single thread
We can not solve this case as single thread cannot work on multiple tasks
 
4. Program to illustrate no 4.Performing multiple task from multiple thread
import java.lang.*;
class Test1 extends Thread
{
    public void run()
    {
    System.out.println("video playing ");
    }
}
class Test2 extends Thread
{
    public void run()
    {
    System.out.println("audio playing ");
    }
}
class Test3 extends Thread
{
    public void run()
    {
    System.out.println("status bar displaying ");
    }
}
    
  public class Testmul
   {
    public static void main(String args[])
    {
    Test1 t1 = new Test1();
    t1.start();

    Test2 t2 = new Test2();
    t2.start();

    Test3 t3 = new Test3();
    t3.start();
    }
  }
Output:
vl@ubuntu:~$ javac Testmul.java
vl@ubuntu:~$ java Testmul
video playing
audio playing
status bar displaying 

Ex3:
class MulThread extends Thread
{
private int number;
//class constructor
public MulThread(int number)
{
this.number = number;
}
public void run()
{
int counter = 0; 
int numInt = 0;
//prints the number till specified number is reached, starting from 10 
try
{
do
{
numInt = (int) (counter + 10); 
System.out.println(this.getName() + " printing " + numInt); 
Thread.sleep(1000);
counter++;
}while(numInt != number);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("**"+this.getName() + " Printed " + counter + " Times.**");
}
}
class UseMulThread
{
public static void main(String [] args)
{
System.out.println("Starting Thread1"); 
Thread t1 = new MulThread(15); 
       t1.start();
System.out.println("Starting Thread2"); 
Thread t2 = new MulThread(20); 
t2.start();
}
}

Output:
C:\Users\Student\Desktop\java prg>javac MulThread.java
C:\Users\Student\Desktop\java prg>java UseMulThread
Starting Thread1
Starting Thread2
Thread-0 printing 10
Thread-1 printing 10
Thread-1 printing 11
Thread-0 printing 11
Thread-1 printing 12
Thread-0 printing 12
Thread-1 printing 13
Thread-0 printing 13
Thread-0 printing 14
Thread-1 printing 14
Thread-1 printing 15
Thread-0 printing 15
Thread-1 printing 16
**Thread-0 Printed 6 Times.**
Thread-1 printing 17
Thread-1 printing 18
Thread-1 printing 19
Thread-1 printing 20
**Thread-1 Printed 11 Times.**

Servlet - JSP Programs

JSP(Java Server Pages) Programs : JavaServer Pages (JSP) is a Java standard technology that enables you to write dynamic data-driven pages f...