Synchronization in Threads

 Synchronization in Threads


// Synchronization in Threads

// Inter Thread Communication


class Que

{

int N;

boolean Flag = false;


synchronized public int get()   // int mtd void

{

while(!Flag)

{

try

{

wait();

}

catch(Exception e)

{

System.out.println(e);

}

}

System.out.println("Consumed = "+N);

Flag = false;

notify();

return N;

}

synchronized void put(int n) // void mtd int

{

while(Flag) //2 

{

try

{

wait();

}

catch(Exception e)

{

System.out.println(e);

}

}

this.N = n; //3

System.out.println("Produced = "+N);

Flag = true; //4

notify();

}

}


class Producer extends Thread

{

Que Q;

Producer(Que q)

{

super("PT");

this.Q = q;

}

public void run()

{

for(int i=1;i<=5;i++)

Q.put(i);

}

}

class Consumer extends Thread

{

Que Q;

Consumer(Que q)

{

super("CT");

this.Q = q;

}

public void run()

{

for(int i=1;i<=5;i++)

Q.get();

}

}


class PC

{

public static void main(String as[])

{

Que q = new Que();

Producer p = new Producer(q);

Consumer c = new Consumer(q);

p.start();

c.start();

}

}

Runnable lnterface

 Runnable Interface


// Create Threads using Runnable Interface 


class NewThd implements Runnable

{

Thread t;

NewThd()

{

t = new Thread(this, "CT");

System.out.println(t);

}

public void run()

{

try

{

for(int i=0;i<5;i++)

{

System.out.println(t.getName()+" "+i);

Thread.sleep(1000);

}

}

catch(Exception e)

{

System.out.println(e);

}

}

}


class Demo_RunnableIntf

{

public static void main(String as[])

{

NewThd NT = new NewThd();

NT.t.start();

Thread T = Thread.currentThread();

T.setName("MT");

try

{

for(int i=0;i<5;i++)

{

System.out.println(T.getName()+" "+i);

Thread.sleep(1000);

}

}

catch(Exception e)

{

System.out.println(e);

}                    

}

}

Thread Class

 Thread Class 


// Create Threads using Thread class 


class NewThd extends Thread

{

NewThd()

{

super("CT");

System.out.println(this);

}

public void run()

{

try

{

for(int i=0;i<5;i++)

{

System.out.println(this.getName()+" "+i);

Thread.sleep(1000);

}

}

catch(Exception e)

{

System.out.println(e);

}

}

}


class Demo_ThdClass

{

public static void main(String as[])

{

NewThd NT = new NewThd();

NT.start();

Thread T = Thread.currentThread();

T.setName("MT");

try

{

for(int i=0;i<5;i++)

{

System.out.println(T.getName()+" "+i);

Thread.sleep(1000);

}

}

catch(Exception e)

{

System.out.println(e);

}                    

}

}

Inter Thread Communication

Inter Thread Communication  


// InterThread Communication


import java.io.*;

import java.util.Random;


class Que

{

int n;

boolean Flag = false;

int counter=0;

synchronized void put(int x)

{

while(Flag==true)

{

try

{

wait();

}

catch(InterruptedException e)

{

System.out.println(e);

}

}

this.n = x;

Flag=true;

notifyAll();

}

synchronized int get()

{

while(Flag==false)

{

try

{

wait();

}

catch(InterruptedException e)

{

System.out.println(e);

}

}

counter++;

if(counter==3)

{

Flag=false;

notify();

counter=0;

}

return this.n;

}

}


class Producer extends Thread

{

Que q;

Producer(Que obj)

{

super("PThd");

q = obj;

}

public void run()

{

int i = 0;

while(i<5)

{

Random rand = new Random();

int rn = rand.nextInt(100)%10;

q.put(rn);

System.out.println("Value sent = "+rn);

i++;

try{

this.sleep(500);

}

catch(Exception e)

{}

}

System.exit(0);

}

}


class Consumer1 extends Thread

{

Que q;

int sq;

Consumer1(Que obj)

{

super("CThd1");

q=obj;

this.setPriority(9);

}

public void run()

{

while(true)

{

int val = q.get();

System.out.println(this.getName()+" - Square = "+(val*val));

try{

this.sleep(500);

}

catch(Exception e)

{}

}

}

}


class Consumer2 extends Thread

{

Que q;

int cu;

Consumer2(Que obj)

{

super("CThd2");

q=obj;

this.setPriority(7);

}

public void run()

{

while(true)

{

int val = q.get();

System.out.println(this.getName()+" - Cube = "+(val*val*val));

try{

this.sleep(500);

}

catch(Exception e)

{}

}

}

}


class Consumer3 extends Thread

{

Que q;

int cu;

Consumer3(Que obj)

{

super("CThd3");

q=obj;

this.setPriority(5);

}

public void run()

{

while(true)

{

int val = q.get();

long fact=1;

for(int i=1;i<=val;i++)

fact=fact*i;

System.out.println(this.getName()+" - Factorial = "+fact);

try{

this.sleep(500);

}

catch(Exception e)

{}

}

}

}


class MultiThdPgm

{

public static void main(String as[])throws Exception

{

Que Q = new Que();

Producer P = new Producer(Q);

Consumer1 C1 = new Consumer1(Q);

Consumer2 C2 = new Consumer2(Q);

Consumer3 C3 = new Consumer3(Q);

P.start();

C1.start();

C2.start();

C3.start();

}

}



/*


sample output


>javac MultiThdPgm.java

>java MultiThdPgm


Value sent = 9

CThd1 - Square = 81

CThd2 - Cube = 729

CThd3 - Factorial = 362880


Value sent = 4

CThd1 - Square = 16

CThd2 - Cube = 64

CThd3 - Factorial = 24


Value sent = 5

CThd1 - Square = 25

CThd2 - Cube = 125

CThd3 - Factorial = 120


Value sent = 2

CThd1 - Square = 4

CThd2 - Cube = 8

CThd3 - Factorial = 2


Value sent = 3

CThd1 - Square = 9

CThd2 - Cube = 27

CThd3 - Factorial = 6


>

Static Keyword in Java

 Static Keyword in Java


//Static keyword


class Counter 

{

static int N;

static 

{

System.out.println("Static block executed.");

}

Counter()

{

N++;

System.out.println("Object created.");

System.out.println("N = "+N);

}

static void fnDisplay()

{

System.out.println("Total Number of Objects = "+N);

}

}


class Static_Demo

{

public static void main(String as[])

{

Counter obj1 = new Counter();

Counter obj2 = new Counter();

Counter obj3 = new Counter();

// Calling static function using Object

Counter.fnDisplay();

// Calling static function using class name

obj3.fnDisplay();

}

}

Super Keyword in Java

 Super Keyword in Java


// Super Keyword


class Rectangle

{

int l, b;

Rectangle(int x, int y)

{

l = x; 

b = y;

}

void fnArea()

{

System.out.println("Area = "+(l*b));

}

}


class Box extends Rectangle

{

int h;

Box(int x, int y, int z)

{

super(x,y);

h = z;

}

void fnVolume()

{

System.out.println("Length = "+super.l);

System.out.println("Breadth = "+super.b);

super.fnArea();

System.out.println("Volume = "+(l*b*h));

}

}


class SuperKW1

{

public static void main(String as[])

{

Box obj = new Box(2,3,4);

obj.fnVolume();

}

}


String Handling

 

String 


// String functions


import java.util.*;


class StrHandling

{

public static void main(String as[])

{

String s[] = new String[10];

Scanner sc = new Scanner(System.in);


System.out.print("Enter Number of Strings : ");

int N = Integer.parseInt(sc.nextLine());


System.out.println("Enter Strings : ");

for(int i = 0; i < N; i++)

s[i] = sc.nextLine();


//Sort

for(int i=0;i<N-1;i++)

{

for(int j=i+1;j<N;j++)

{

if((s[i].compareTo(s[j]))>0)

{

String tmp = s[i];

s[i] = s[j];

s[j] = tmp;

}

}

}


System.out.println("Sorted Strings : ");

for(int i = 0;i<N;i++)

System.out.println(s[i]);

}

}


Exception Handling

 Exception Handling in Java


// Exception Handling in Java

// Keywords: try, catch, throw, throws and finally,

// Built - in and user-defined exceptions

 

import java.io.*;

import java.util.*;

 

// User-defined exception class

class InvalidAgeException extends Exception

{

    // Constructor accepts a message and passes it to the superclass Exception

    public InvalidAgeException(String message)

    {

         super(message);

    }

}

 


 

// Class for age validation

class AgeValidation

{

    // Method that validates age

    // 'throws' declares that this method might throw InvalidAgeException

    public void validateAge(int age) throws InvalidAgeException

    {

         // 'throw' is used to explicitly create and throw an exception object

         if (age < 0)

         {

throw new InvalidAgeException("Invalid age value. Age cannot be negative.");

        }

        // If age is valid, print the message

        System.out.println(age + " - Valid age.");

    }

}

 

public class ExceptionHandling

{

    public static void main(String[] args)

    {

         int age;

         AgeValidation av = new AgeValidation(); // Create AgeValidation object

         Scanner sc = new Scanner(System.in);    // Scanner for user input

 

         try

         {

             // Input from user

             System.out.print("Enter Age : ");

             age = sc.nextInt();

 

             // Validate the input age

             av.validateAge(age);

         }

         // Catch block for user-defined exception

         catch (InvalidAgeException e)

         {

             System.out.println("Caught Exception: " + e.getMessage());

         }

        // Catch block for Built-in Exception

        catch(InputMismatchException e)

        {

             System.out.println("Built-in Exception: " + e);

         }

         // Catch block for other general exceptions

         catch (Exception e)

         {

             System.out.println("General Exception: " + e);

        }

        // The finally block always executes, whether exception occurs or not

         finally

         {

             System.out.println("End of Program.");

        }

    }

}


Interfaces

 

Interfaces

 

// Interface

 

interface Shape

{

    public void printArea();

}

 

// Rectangle class

class Rectangle implements Shape

{

    double dim1, dim2;

   

    Rectangle(double length, double breadth)

    {

        dim1 = length;

        dim2 = breadth;

    }

 

    public void printArea()

    {

        double area = dim1 * dim2;

        System.out.printf("Area of Rectangle = %.2f%n", area);

    }

}

 

// Triangle class

class Triangle implements Shape

{

    double dim1, dim2;

   

    Triangle(double base, double height)

    {

        dim1 = base;

        dim2 = height;

    }

 

    public void printArea()

    {

        double area = 0.5 * dim1 * dim2;

        System.out.printf("Area of Triangle = %.2f%n", area);

    }

}

 

// Circle class

class Circle implements Shape

{

    double dim1;

   

    Circle(double radius)

    {

        dim1 = radius;

    }

 

    public void printArea()

    {

        double area = Math.PI * dim1 * dim1;

        System.out.printf("Area of Circle = %.2f%n", area);

    }

}

 

public class Demo_Interface

{

    public static void main(String as[])

    {

        Rectangle r = new Rectangle(10, 5);

        r.printArea();

 

        Triangle t = new Triangle(6, 8);

        t.printArea();

 

        Circle c = new Circle(7);

        c.printArea();

    }

}

Abstract class

 // Abstract class

abstract class Shape 

{

    double dim1, dim2;


    Shape(double a) 

{

        dim1 = a;

        dim2 = 0;

    }

Shape(double a, double b) 

{

        dim1 = a;

        dim2 = b;

    }


    // Abstract method

    abstract void printArea();

}


// Rectangle class

class Rectangle extends Shape 

{

    Rectangle(double length, double breadth) 

{

        super(length, breadth);

    }


    void printArea() 

{

        double area = dim1 * dim2;

        System.out.printf("Area of Rectangle = %.2f%n", area);

    }

}


// Triangle class

class Triangle extends Shape 

{

    Triangle(double base, double height) 

{

        super(base, height);

    }


    void printArea() 

{

        double area = 0.5 * dim1 * dim2;

        System.out.printf("Area of Triangle = %.2f%n", area);

    }

}


// Circle class

class Circle extends Shape 

{

    Circle(double radius) 

{

        super(radius);

    }


    void printArea() 

{

        double area = Math.PI * dim1 * dim1;

        System.out.printf("Area of Circle = %.2f%n", area);

    }

}


public class Demo_Abstract 

{

    public static void main(String as[]) 

{

        Rectangle r = new Rectangle(10, 5);

        r.printArea();


        Triangle t = new Triangle(6, 8);

        t.printArea();


        Circle c = new Circle(7);

        c.printArea();

    }

}


Inheritance and Packages

 

Inheritance and Packages

 

package PaySlip;

 

public class PaySlipGenerator

{

    public void PaySlip(double basicPay)

    {      

        double da = 0.97 * basicPay;        

        double hra = 0.10 * basicPay;       

        double pf = 0.12 * basicPay;

        double staffClubFund = 0.001 * basicPay;

        double grossSalary = basicPay + da + hra;

        double netSalary = grossSalary - (pf + staffClubFund);

       

        System.out.println("Basic Pay        : " + basicPay);

        System.out.println("DA (97%)         : " + da);

        System.out.println("HRA (10%)        : " + hra);

        System.out.println("PF (12%)         : " + pf);

        System.out.println("Staff Club (0.1%): " + staffClubFund);

        System.out.println("Gross Salary     : " + grossSalary);

        System.out.println("Net Salary       : " + netSalary);

    }

}


 

// Hierachical inheritance and Packages

// Employee Payroll System

 

import java.util.*;

import PaySlip.*;

 

class Employee

{

    String empName, empId, address, mailId;

    long mobileNo;

 

    Employee(String name, String id, String addr, String mail, long mobile)

    {

        empName = name;

        empId = id;

        address = addr;

        mailId = mail;

        mobileNo = mobile;

    }

   

    // Display employee details

    void displayDetails()

    {

        System.out.println("Employee ID      : " + empId);

        System.out.println("Employee Name    : " + empName);

        System.out.println("Address          : " + address);

        System.out.println("Mail ID          : " + mailId);

        System.out.println("Mobile No        : " + mobileNo);

    }

   

}

 

class Programmer extends Employee

{

    public double basicPay;

   

    Programmer(String name, String id, String addr, String mail, long mobile, double bp)

    {

        super(name, id, addr, mail, mobile);

         basicPay = bp;

    }

}

 

class AssistantProfessor extends Employee

{

    public double basicPay;

   

    AssistantProfessor(String name, String id, String addr, String mail, long mobile, double bp)

    {

        super(name, id, addr, mail, mobile);

         basicPay = bp;

    }

}

 

class AssociateProfessor extends Employee

{

    public double basicPay;

   

    AssociateProfessor(String name, String id, String addr, String mail, long mobile, double bp)

    {

        super(name, id, addr, mail, mobile);

         basicPay = bp;

    }

}

 

class Professor extends Employee

{

    public double basicPay;

   

    Professor(String name, String id, String addr, String mail, long mobile, double bp)

    {

        super(name, id, addr, mail, mobile);

         basicPay = bp;

    }

}

 

public class EmployeePaySlip

{

    public static void main(String as[])

    {

         PaySlipGenerator psg = new PaySlipGenerator();

        

        Programmer p = new Programmer("Alice", "EMP101", "Chennai", "alice@gmail.com", 9876543210L, 50000);

         System.out.println("\nPay Slip - Programmer. ");

        p.displayDetails();

         psg.PaySlip(p.basicPay);

 

        AssistantProfessor ap = new AssistantProfessor("Bob", "EMP102", "Bangalore", "bob@gmail.com", 9876543211L, 60000);

         System.out.println("\nPay Slip - Assistant Professor. ");

         ap.displayDetails();

        psg.PaySlip(ap.basicPay);

 

        AssociateProfessor asp = new AssociateProfessor("Charlie", "EMP103", "Delhi", "charlie@gmail.com", 9876543212L, 75000);

        System.out.println("\nPay Slip - Associate Professor. ");

         asp.displayDetails();

         psg.PaySlip(asp.basicPay);

 

        Professor prof = new Professor("David", "EMP104", "Mumbai", "david@gmail.com", 9876543213L, 90000);

         System.out.println("\nPay Slip - Professor. ");

        prof.displayDetails();

         psg.PaySlip(prof.basicPay);

    }

}