Multithreaded Programming

Multithreading is a conceptual programming paradigm where a program is divided into two or more sub-programs which can be implemented at the same time in parallel.For example one sub-program can display an animation on the screen while another may build the next animation to be displayed.This is something similar to dividing a task into subtasks and assigning them to different people for execution independently and simultaneously.

                       A Thread is similar to a program that has a single flow of control.It has a beginning,a body and an end and executes command sequentially.A unique property of java is its support for

multithreading.That is,java enables us to use multiple flows of control in developing programs. Each flow of control may be thought of as a separate tiny program known as thread that run in parallel.A program that contain multiple control flow is known as Multithreaded program.

Creating Threads:- creating threads in java is simple.threads are implemented in the form of objects that contain a method called run().The run() method is the major part of any thread.it makes up the entire body of a thread and is the only method in which the thread’s behaviour can be implemented.

Syntax to Write run() Method:-

 

public void run()

{

……………………..

……………………..

}

The run() method should be invoked by an object of the concerned thread.This can be achieved by creating the thread and initiating it with the help of another method called start().

A new thread can be created n two ways:-

1.) By Creating A Thread Class:-  Define a class that extends Thread class and override its run() method  with the code required by the thread.

2.) By Converting a class to a thread:-  define a class that implements Runnable interface.The Runnable interface has only one method,run() that is to be defined in the method with the code to be executed by the thread.

Extending The Thread Class:-  We can  make our class runnable as thread by extending the class java.lang.Thread.This gives us access to all the thread methods directly.It can be done by following steps:-

1.) Declare the class as extending the Thread class.

2.) Implement run() method that is responsible for executing the sequence of the code that the thread will execute.

3.) Create a thread object and call the start() method to initiate the execution.

 

Example Program:-


class A extends Thread

{

public void run()

{

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

{

System.out.println(“Thread A running i=” + i);

}

System.out.println(“Thread A exits”);

}

}

class B extends Thread

{

public void run()

{

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

{

System.out.println(“Thread B running j=” + j);

}

System.out.println(“Thread B exits”);

}

}

class C extends Thread

{

public void run()

{

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

{

System.out.println(“Thread C running k=” + k);

}

System.out.println(“Thread C exits”);

}

}

public class threadtest

{

public static void main(String args[])

{

A a1=new A();

B b1=new B();

C c1=new C();

System.out.println(“Main thread Starts”);

System.out.println(“Thread A Starts”);

a1.start();

System.out.println(“Thread B starts”);

b1.start();

System.out.println(“thread c starts”);

c1.start();

System.out.println(“thread Main ends”);

}

}

 

 

Advertisements

Introduction To Applets In Java

Applets are small java programs that are primarily used in Internet computing. They can be transported over the internet from one computer to another the computer and run using the Applet Viewer or any Web browser that supports java.An applet,like any application  program,can do many things for us.It can perform arithmetic operations,display graphics,play sounds,accept user input,create  animation and play interactive games.Java has enabled them to create and use fully interactive multimedia We documents.A web page can now contain only a simple text or a static image but also a java applet which,when run can produce graphics sounds and moving images.

 

Local And Remote Applets:- We can embed applet into web pages in two ways. One,we can write our own applets and embed them into Web pages.Second, we can download an applet from a remote computer system and then embed it into a web pages.

                                                                  An applet developed locally and stored in a local systems known as local applet.When a Web page is trying to find a local applet,it does not need to use the internet and therefore the local system does not require the internet connection.

                                    A remote applet is that which is developed by someone else and stored on a remote computer connected to the internet.If our system is connected to the internet,we can download the remote applet onto our system via at the internet and run it.

                                   In order to locate and load a remote applet,we must know the applet’s address on the web.This address on the web is known as Uniform Resource Locator(URL) and must be specified  in the applet’s HTML document as the value on the CODEBASE attribute.

Difference Between Applets And Application

Although both the applets and stand alone application are java programs,there are significance differences between them.Applets are not full-featured application programs.they are usually written to accomplish a small task or a component of a task.Since they are usually designed for use on the Internet,they impose certain limitations and restriction in their design.

 

  • Applets do not use the main() method for initiating the execution of the code.Applets when loaded,automatically call certain methods of applet class to start  and execute the applet code.
  • unlike stand alone applications,applets cannot be run independently.They are run from inside a web page using a special feature known as HTML tag.
  •  Applets cannot read from or write to the files in type local computer.
  • Applets cannot communicates with other servers on the network.
  • Applets cannot cannot run any program from the local computer.
  • Applets are restricted from using libraries from other languages such as C or C++

Program to Pass Parameter To Applets using Param Tag

import java.awt.*;

import java.applet.*;

public class HelloJavaParam extends Applet

{

String str;

public void init()

{

str=getParameter(“String”);

if(str==null)

str=”java”;

str=”hello”+str;

}

 public void paint(Graphics g)

{

g.drawString(str,10,100);

}

}

 

 

 

HTML CODE FOR  HelloJavaParam

 

<html>

<! parameterised html file>

<head>

<title>Welcome to java applets </tittle>

</head>

<body>

<applet code=HelloJavaParam.class

      width=400

      height=200>

<param name=”String” value=”Applet!”>

</applet?

</body>

 

</html>

 


OUTPUT 

 

 

Basics To Write Applet Code

While writing applet code we must take care to import two classes ,Applet And Graphics from the java class library.The Applet class which is contained  in the Java.applet package provides life and behaviour to the applet through its methods such as init(),start() and point().Unlike the application where java calls the main() method directly to initiate the execution of the program,when an applet is loaded,java automatically calls a series of applet class for starting,running and stopping the applet code.The Applet class therefore maintains the life-cycle  of an object.

   The paint() method of  the Applet class,when it is called,actually displays the result of the applet code on the screen.The output may be text,graphics or sound.the paint() method,which requires a Graphics object as an argument,this is shown as below:-

       

         public void paint(Graphics g)

 This requires that the applet code imports the java.awt package that contains the Graphics class.All output operations of an applet are performed using the methods defined in the Graphics class.It is the thus clear from the above discussions that an applet code will have a general as shown:-

           

                   import java.awt.*;

                   import java.applet.*;

                   public class appletname extends Applet

                   {

                        ………………………..

                        ………………………..

                        public void paint (Graphics g)

                         {

                              ………………………………..

                              ………………………………..

                             }

                             ………………………………….

                             ………………………………….

                         }

The appletclassname is the main class for the applet.When the applet is loaded,Java creates an istance of this class,and then a series of  Applet class methods are called on that instance to execute the code.

 

Example Program:-

 

import java.awt.*;

import java.applet.*;

public class Hellojava extends Applet

{

     public void paint(Graphics g)

     {

            g.drawString(“Hello Java”,10,100)

       }

}

 

What Is Not Possible Using Inheritance In Java

1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.

2. Members that have default accessibility in the super-class are also not inherited by sub-classes in other   packages, as these members are only accessible by their simple names in sub-classes within the same     package as the super-class.

3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.

4. A subclass can extend only one superclass

 

class Vehicle {

 

// Instance fields

int noOfTyres;         // no of tyres

private boolean accessories;            // check if accessorees present or not

protected String brand;                   // Brand of the car

// Static fields

private static int counter;                 // No of Vehicle objects created

// Constructor

Vehicle() {

System.out.println(“Constructor of the Super class called”);

noOfTyres = 5;

accessories = true;

brand = “X”;

counter++;

}

                                                       // Instance methods

public void switchOn() {

accessories = true;

}

public void switchOff() {

accessories = false;

}

public boolean isPresent() {

return accessories;

}

private void getBrand() {

System.out.println(“Vehicle Brand: ” + brand);

}

                                                                // Static methods

public static void getNoOfVehicles() {

System.out.println(“Number of Vehicles: ” + counter);

}

}

class Car extends Vehicle

{

private int carNo = 10;

public void printCarInfo() {

System.out.println(“Car number: ” + carNo);

System.out.println(“No of Tyres: ” + noOfTyres);                         // Inherited.

//  System.out.println(“accessories: ”    + accessories);                  // Not Inherited.

System.out.println(“accessories: ” + isPresent());                          // Inherited.

//        System.out.println(“Brand: ”     + getBrand());                    // Not Inherited.

System.out.println(“Brand: ” + brand);                                         // Inherited.

//  System.out.println(“Counter: ”    + counter);                           // Not Inherited.

getNoOfVehicles(); // Inherited.

}

public class VehicleDetails

{                      // (3)

public static void main(String[] args) {

new Car().printCarInfo();

}

}

 

Output

Constructor of the Super class called

Car number: 10

No of Tyres: 5

accessories: true

Brand: X

Number of Vehicles: 1

Basic Arithmetic Operators

The basic arithmetic operations-addition,subtraction,multiplication and division-all behave as you would expect for all numeric types.The minus operator also has a unary form that negates its single operand.Remenber that when the division operator is applied to an integer type,there will be no fractional component attached to the  result.

           The following simple example program demonstrates the arithamtic operators.It also illustrates the difference between floating-point division and integer division.

 

//Demonstrate the basic arithmetic operators.

class BasicMath

{

public static void main(String args[])

{

System.out.println(“Integer Arithmatic”);

int a=1+1;

int b=a*3;

int c=b/4;

int d=c-a;

int e=-d;

System.out.println(“a=”+a);

System.out.println(“b=”+b);

System.out.println(“c=”+c);

System.out.println(“d=”+d);

System.out.println(“e=”+e);

//Arithmatic using doubles

System.out.println(“\n Floating point Arithmatic”);

double da=1+1;

double db=da*3;

double dc=db/4;

double dd=dc-a;

double de=-dd;

System.out.println(“da=”+da);

System.out.println(“db=”+db);

System.out.println(“dc=”+dc);

System.out.println(“dd=”+dd);

System.out.println(“de=”+de);

}

}