Movie Ticket Booking App 3

 class TotalEarning extends Thread {


  int earning = 0;

  public void run() {
    synchronized (this) {
      for (int i = 0; i < 10; i++) {
        earning += 100;
      }
      this.notify();
    }
  }
}

public class MovieBookApp3 {

  public static void main(String[] args) {
    TotalEarning te = new TotalEarning();
    te.start();
    synchronized (te) {
      try {
        te.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("Total Earning = " + te.earning);
    }
  }
}

Movie Ticket Booking App

 

class BookTheaterSeat {

  static int total_seats = 20;

  //synchronized method
  static synchronized void bookSeat(int seats) {
    if (total_seats >= seats) {
      System.out.println(seats + " Seats booked Successfully");
      total_seats -= seats;
      System.out.println("Total seats available= " + total_seats);
    } else {
      System.out.println("Booking failed due to less seat are available");
      System.out.println("Seats available are : " + total_seats);
    }
  }
}

class MyThread1 extends Thread {

  BookTheaterSeat b;
  int seats;

  MyThread1(BookTheaterSeat b, int seats) {
    this.b = b;
    this.seats = seats;
  }

  @Override
  public void run() {
    b.bookSeat(seats);
  }
}

class MyThread2 extends Thread {

  BookTheaterSeat b;
  int seats;

  MyThread2(BookTheaterSeat b, int seats) {
    this.b = b;
    this.seats = seats;
  }

  @Override
  public void run() {
    b.bookSeat(seats);
  }
}

public class MovieBookApp2 extends Thread {

  int seats;
  static BookTheaterSeat b;

  @Override
  public void run() {
    b.bookSeat(seats);
  }

  public static void main(String[] args) {
    BookTheaterSeat b1 = new BookTheaterSeat();
    MyThread1 t1 = new MyThread1(b1, 7);
    t1.start();

    MyThread2 t2 = new MyThread2(b1, 6);
    t2.start();

    BookTheaterSeat b2 = new BookTheaterSeat();
    MyThread1 t3 = new MyThread1(b2, 5);
    t3.start();

    MyThread2 t4 = new MyThread2(b2, 6);
    t4.start();
  }
}

Movie Ticket Booking App

 

class BookTheaterSeat {

  int total_seats = 10;

  //synchronized method
  synchronized void bookSeat(int seats) {
    if (total_seats >= seats) {
      System.out.println(seats + " Seats booked Successfully");
      total_seats -= seats;
      System.out.println("Total seats available= " + total_seats);
    } else {
      System.out.println("Booking failed less seat are available");
      System.out.println("Seats available are : " + total_seats);
    }
  }
}

public class MovieBookApp extends Thread {

  int seats;
  static BookTheaterSeat b;

  @Override
  public void run() {
    b.bookSeat(seats);
  }

  public static void main(String[] args) {
    b = new BookTheaterSeat();
    MovieBookApp mb1 = new MovieBookApp();
    mb1.seats = 3;
    mb1.start();

    MovieBookApp mb2 = new MovieBookApp();
    mb2.seats = 6;
    mb2.start();
  }
}

Difference between Method and Thread

 public class MethodAndThread extends Thread {


  public void run() {
    try {
      for (int i = 0; i < 5; i++) {
        System.out.println(i + ":" + Thread.currentThread().getName());
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) {
    MethodAndThread mt1 = new MethodAndThread();
    MethodAndThread mt2 = new MethodAndThread();
    //Thread1
    //   mt1.start();
    //Thread2
    //Both threads will run simultaneously
    //  mt2.start();
    //calling run() method
    mt1.run();
    //calling run() method
    //method will run one after another
    mt2.run();
  }
}

Thread Joining

 

public class JoinMainThread extends Thread {

  static Thread mainthread;

  public void run() {
    try {
      mainthread.join();
      for (int i = 0; i < 5; i++) {
        System.out.println("child thread : " + i);
        Thread.sleep(1000);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    mainthread = Thread.currentThread();
    JoinMainThread jm = new JoinMainThread();
    jm.start();

    try {
      for (int i = 0; i < 5; i++) {
        System.out.println("main thread : " + i);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Thread Interruption

 

public class IsInterrupted extends Thread {
  @Override
  public void run() {
    //change the status of interrupted from true to false
    //only if thread is interrupted
    //interrupted() is a static method
    //can be invoked using thread.interrupted()
    System.out.println(Thread.interrupted()); //true->false
    //does not change the interrupted status
    //only gives the status
    //not a static method
    //have to be invoked using currentThread()
    System.out.println(Thread.currentThread().isInterrupted());
    try {
      for (int i = 1; i <= 5; i++) {
        System.out.println(i);
        Thread.sleep(1000);
      }
    } catch (Exception e) {
      System.out.println("Thread interrupted : " + e);
    }
  }

  public static void main(String[] args) {
    IsInterrupted ti = new IsInterrupted();
    ti.start();
    // ti.interrupt();
  }
}

Daemon Thread

 

public class DaemonThread extends Thread {

  @Override
  public void run() {
    System.out.println("inside user created thread");

    if (Thread.currentThread().isDaemon()) {
      System.out.println("It is a Daemon Thread");
    } else {
      System.out.println("It is not a daemon thread");
    }
  }

  public static void main(String[] args) {
    System.out.println("main thread");
    //We can not set a thread as daemon thread after running
    //that why this will give exeption for main
    //i.e we can not set main thread as deamon thread
    //Thread.currentThread().setDaemon(true);
    DaemonThread dt = new DaemonThread();
    dt.setDaemon(true);
    dt.start();
    // System.out.println(dt.isAlive());
  }
}

Using Yield Method in a Thread

 

public class Yield extends Thread {

  public void run() {
    //to stop thread 0
    Thread.yield();
    for (int i = 0; i < 5; i++) {
      System.out.println(i + ":" + Thread.currentThread().getName());
    }
  }

  public static void main(String[] args) {
    Yield y1 = new Yield();
    y1.start();
    //to stop main method and other thread get a chance to execute
    Thread.yield();
    for (int i = 0; i < 5; i++) {
      System.out.println(Thread.currentThread().getName() + ":" + i);
    }
  }
}

Performing sngle task using Multiple Thread

 

//Performing single task using multiple thread
public class SingleTaskMultipleThread extends Thread {

  @Override
  public void run() {
    System.out.println("Perfroming task");
  }

  //driver method
  public static void main(String[] args) {
    //thread1
    SingleTaskMultipleThread stmt1 = new SingleTaskMultipleThread();
    //invoking thread1
    stmt1.start();
    //thread2
    SingleTaskMultipleThread stmt2 = new SingleTaskMultipleThread();
    //invoking thread2
    stmt2.start();
    //thread3
    SingleTaskMultipleThread stmt3 = new SingleTaskMultipleThread();
    //invoking thread3
    stmt3.start();
  }
}

Thread Naming

 

class ThreadNaming extends Thread {

  ThreadNaming(String threadName) {
    super(threadName);
  }

  public void run() {
    System.out.println("Thread is running");
  }
}

public class NamingThread {

  public static void main(String[] args) {
    ThreadNaming tn1 = new ThreadNaming("java");
    ThreadNaming tn2 = new ThreadNaming("Invent");

    System.out.println("Thread th1 name : " + tn1.getName());
    System.out.println("Thread th2 name : " + tn2.getName());

    System.out.println("Thread th1 id : " + tn1.getId());
    System.out.println("Thread th2 id : " + tn2.getId());

    System.out.println(
      "Thread main Priority : " + Thread.currentThread().getPriority()
    );
    System.out.println("Thread th1 : " + tn1.getPriority());
    System.out.println("Thread th2 : " + tn2.getPriority());
  }
}

Performing multiple Task Using Multiple Threads

 

//performing multiple task using multiple threads
class PlayMusic extends Thread {

  @Override
  public void run() {
    System.out.println("Playing music");
  }
}

class PlayVideo extends Thread {

  @Override
  public void run() {
    System.out.println("Video is being played");
  }
}

class OpenBrowser extends Thread {

  @Override
  public void run() {
    System.out.println("Brower is Running");
  }
}

public class MultiTaskMultiThread {

  public static void main(String[] args) {
    PlayMusic pm = new PlayMusic();
    pm.start();
    PlayVideo pv = new PlayVideo();
    pv.start();
    OpenBrowser ob = new OpenBrowser();
    ob.start();
  }
}

Demo program to get Driving License

 

class Medical extends Thread {

  public void run() {
    System.out.println("Medical Started");
    try {
      Thread.sleep(5000);
      System.out.println("medical completed");
      System.out.println("----------------------------------------");
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

class TestDrive extends Thread {

  public void run() {
    System.out.println("Test Drive Started");
    try {
      Thread.sleep(3000);
      System.out.println("test driver passed safely");
      System.out.println("-----------------------------------------------");
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

class OfficerSign extends Thread {

  public void run() {
    System.out.println("File handed over to Officer");
    try {
      Thread.sleep(1000);
      System.out.println("officer signed the documents");
      System.out.println("-----------------------------------------------");
      Thread.sleep(1000);

      System.out.println("Licence process completed");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

public class LicenceDemo {

  public static void main(String[] args) {
    try {
      Medical med = new Medical();
      med.start();
      med.join();

      TestDrive td = new TestDrive();
      td.start();
      td.join();

      OfficerSign os = new OfficerSign();
      os.start();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

Performing methods available for a thread

 

public class CurrentThreadName1 extends Thread {

  @Override
  public void run() {
    //setting name of thread
    Thread.currentThread().setName("User Created Thread");
    //getting name of thread with a msg
    System.out.println("thread running : " + Thread.currentThread().getName());
  }

  public static void main(String[] args) {
    System.out.println("hello : " + Thread.currentThread().getName());
    CurrentThreadName1 ct = new CurrentThreadName1();
    //thread name can be at both place i.e
    //here i.e in main method
    //in run method
    // ct.setName("JavaInvent");
    ct.start();
    //checking if current thread(i.e main thread) is alive or not
    System.out.println(
      Thread.currentThread().getName() + ":" + Thread.currentThread().isAlive()
    );
    //checking if user created thread is alive or not
    System.out.println(ct.getName() + ":" + ct.isAlive());
  }
}

Setting and Getting the name of Current Thread

 


public class CurrentThreadName {

  public static void main(String[] args) {
    //to get name of current thread
    System.out.println(Thread.currentThread().getName());
    //to set name of current thread
    Thread.currentThread().setName("javainvent");
    //getting name of current thread after invoking set name
    //main thread name can also be changed
    //main thread is created by JVM
    System.out.println(Thread.currentThread().getName());
    System.out.println(0 / 0);
  }
}

Creating a Thread Using Runnable Interface

 


//performing single task using single thread
//Creating thread by implementing runnable interface
public class CreateThread1 implements Runnable {

  @Override
  public void run() {
    System.out.println("Thread task");
  }

  public static void main(String[] args) {
    CreateThread1 c1 = new CreateThread1();
    Thread th = new Thread(c1);
    th.start();
  }
}

Creating a thread and performing Single task using single Thread

 

//inherits Thread class
//performing single task using single thread
public class CreateThread extends Thread {

  @Override
  public void run() {
    System.out.println("Thread Task");
  }

  public static void main(String[] args) {
    //Creating object of class CreateThread
    CreateThread c1 = new CreateThread();
    //invoking thread using start method;
    c1.start();
    //gives exception, we can not start a thread twice
    c1.start();
  }
}

Java Program to Add, Delete, Replace, Search, Display record of a table using JDBC


//save as DataBaseDetails.proterties

driver = com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
pass =root
//--------------------------------------//

//Java program to connect to Database
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;

public class ConnectionProvider {

  public static Connection con = null;

  public static Connection getConnection() {
    if (con == null) {
      Properties p = new Properties();
      FileInputStream fis = null;
      try {
        fis = new FileInputStream("DataBaseDetails.properties");
        p.load(fis);
        String driver = p.getProperty("driver");
        String url = p.getProperty("url");
        String user = p.getProperty("user");
        String pass = p.getProperty("pass");

        Class.forName(driver);
        Connection con = DriverManager.getConnection(url, user, pass);
        System.out.println("connection Established Successfully");
        return con;
      } catch (Exception e) {
        System.out.println(e);
      }
    }
    return con;
  }
}
//-------------------------------------------//
//save as Student.java

public class Student {

  int rollNo;
  String first_name;
  String last_name;
  String course;
  int fee;

  public void setRollNo(int rollNo) {
    this.rollNo = rollNo;
  }

  public void setFir_name(String first_name) {
    this.first_name = first_name;
  }

  public void setLast_name(String last_name) {
    this.last_name = last_name;
  }

  public void setCourse(String course) {
    this.course = course;
  }

  public void setFee(int fee) {
    this.fee = fee;
  }

  public int getRollNo() {
    return rollNo;
  }

  public String getFirst_name() {
    return first_name;
  }

  public String getLast_name() {
    return last_name;
  }

  public String getCourse() {
    return course;
  }

  public int getFee() {
    return fee;
  }
}
//-----------------------------------------//
//save as StudentImplementation.java
//Java program to add delete update search and display records
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;

public class StudentImplementation {

  //method to add a record
  void add() {
    try {
      //establishing connection with database
      Connection con = ConnectionProvider.getConnection();
      //getting scanner to take input from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the Roll No.");
      int rollNo = sc.nextInt();
      Boolean status = search(rollNo);
      if (status == false) {
        System.out.println("Enter First Name");
        String first_Name = sc.next();
        System.out.println("Enter Last Name");
        String last_Name = sc.next();
        System.out.println("Enter Course Name");
        String course = sc.next();
        System.out.println("Enter fee");
        int fee = sc.nextInt();
        PreparedStatement ps = con.prepareStatement(
          "Insert into Student(RollNo,FirstName,LastName,Course,Fee)values(?,?,?,?,?)"
        );
        ps.setInt(1, rollNo);
        ps.setString(2, first_Name);
        ps.setString(3, last_Name);
        ps.setString(4, course);
        ps.setInt(5, fee);
        ps.executeUpdate();
      } else {
        System.out.println("Roll No. already exists");
      }
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  //method to search a record
  Boolean search(int rollNo) {
    try {
      Connection con = ConnectionProvider.getConnection();
      PreparedStatement ps = con.prepareStatement(
        "select *from student where RollNo=?"
      );
      ps.setInt(1, rollNo);
      ResultSet rs = ps.executeQuery();
      //System.out.println(rs.next());
      return rs.next();
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  //method to display all records in the table
  void display() {
    try {
      Connection con = ConnectionProvider.getConnection();
      PreparedStatement ps = con.prepareStatement("select * from student");
      ResultSet rs = ps.executeQuery();
      System.out.println("Record is as follow:");
      while (rs.next()) {
        System.out.println(
          "Roll No. " +
          rs.getInt(1) +
          " " +
          "First Name " +
          rs.getString(2) +
          " " +
          "Last Name :" +
          rs.getString(3) +
          " " +
          "Course : " +
          rs.getString(4) +
          " " +
          "Fee" +
          rs.getInt(5)
        );
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  //method to delete a record
  void delete(int rollNo) {
    Boolean status = search(rollNo);
    if (status) {
      try {
        Connection con = ConnectionProvider.getConnection();
        PreparedStatement ps = con.prepareStatement(
          "Delete from student where rollNo=?"
        );
        ps.setInt(1, rollNo);
        ps.executeUpdate();
        System.out.println(
          "Record associated with RollNo. " +
          rollNo +
          " has been deleted Successfully"
        );
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
      System.out.println("Roll No. does not exists");
    }
  }

  //method to update the existing record
  void Update(int rollNo) {
    Boolean status = search(rollNo);
    if (status) {
      try {
        //establishing connection with database
        Connection con = ConnectionProvider.getConnection();
        //getting scanner to take input from user
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter First Name");
        String first_Name = sc.next();
        System.out.println("Enter Last Name");
        String last_Name = sc.next();
        System.out.println("Enter Course Name");
        String course = sc.next();
        System.out.println("Enter fee");
        int fee = sc.nextInt();
        PreparedStatement ps = con.prepareStatement(
          "update student set FirstName=?,LastName=?,Course=?,Fee=? where RollNo=?"
        );

        ps.setString(1, first_Name);
        ps.setString(2, last_Name);
        ps.setString(3, course);
        ps.setInt(4, fee);
        ps.setInt(5, rollNo);
        ps.executeUpdate();
        System.out.println("Record updated Successfully");
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
      System.out.println("Roll No. does not exists");
    }
  }

  //driver class
  public static void main(String[] args) {
    StudentImplementation stmp = new StudentImplementation();
    Scanner sc = new Scanner(System.in);
    int num;
    while (true) {
      System.out.println("Press 1 to add a record");
      System.out.println("Press 2 to delete a record");
      System.out.println("Press 3 to update an existing record");
      System.out.println("Press 4 to display all the records available");
      System.out.println("Press 5 to search a record in the given table");
      System.out.println("Press 0 to exit");
      num = sc.nextInt();
      switch (num) {
        case 0:
          {
            System.exit(0);
          }

          break;
        case 1:
          {
            stmp.add();
          }
          break;
        case 2:
          {
            System.out.println("Enter Roll No");
            int rollNo = sc.nextInt();
            stmp.delete(rollNo);
          }
          break;
        case 3:
          {
            System.out.println("Enter Roll No");
            int rollNo = sc.nextInt();
            stmp.Update(rollNo);
          }
          break;
        case 4:
          {
            stmp.display();
          }
          break;
        case 5:
          {
            System.out.println("Enter Roll No");
            int rollNo = sc.nextInt();
            Boolean status = stmp.search(rollNo);
            if (status) {
              System.out.println("Record exist");
            } else {
              System.out.println("Record does not exist!");
            }
          }
          break;
        default:
          {
            System.out.println("Invalid Entry");
          }
      }
    }
  }
}




Google Script for Data Entry Form in Google Spreadsheet

// function to validate the entry made by user in user form function validateEntry (){ // declare a variable and referernece of active goog...