Sunteți pe pagina 1din 96

Java Programming

Dr.S.Kalaivani
Assistant Professor/ Dept.of CSE
IRTT,Erode
Topics to be covered
 Class, Member, Function
 Constructor & its types
 Inheritance
 Interface
 Package
 Polymorphism
Compile time
Runtime
 Exception Handling
 I/O Streams, File Streams
 Object cloning & Serialization
 Thread handling
Java Programming 2
Classes
• A class is a collection of fields (data) and
methods (procedure or function) that operate
on that data.

Circle

centre
radius
circumference()
area()

3
Classes
• A class is a collection of fields (data) and methods (procedure
or function) that operate on that data.
• The basic syntax for a class definition:
class ClassName [extends
SuperClassName]
{
[fields declaration]
[methods declaration]
• Bare bone class} – no fields, no methods

public class Circle {


// my circle class
}
4
Adding Fields: Class Circle with fields
• Add fields
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle

• The fields (data) are also called the instance


varaibles.

5
Adding Methods
• A class with only data fields has no life. Objects
created by such a class cannot respond to any
messages.
• Methods are declared inside the body of the class
but immediately after the declaration of data fields.
• The general form of a method declaration is:

type MethodName (parameter-list)


{
Method-body;
}
6
Adding Methods to Class Circle
public class Circle {

public double x, y; // centre of the circle


public double r; // radius of circle

//Methods to return circumference and area


public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r; Method Body
}
}
7
Data Abstraction
• Declare the Circle class, have created a new
data type – Data Abstraction

• Can define variables (objects) of that type:

Circle aCircle;
Circle bCircle;

8
Sample Program
import java.io.*;
class First
{
static void disp(int []a)
{
for(int i=0;i<a.length;i++)
{
try{
DataInputStream din=new DataInputStream(System.in);
a[i]=Integer.parseInt(din.readLine());
}catch(Exception io){}
System.out.println(a[i]);
}
}

public static void main(String arg[])


{
int a[]=new int[10];
disp(a);
}
}

Java Programming 9
What is a Constructor?
• Constructor is a special method that gets invoked
“automatically” at the time of object creation.
• Constructor is normally used for initializing objects with
default values unless different values are supplied.
• Constructor has the same name as the class name.
• Constructor cannot return values.
• A class can have more than one constructor as long as they
have different signature (i.e., different input arguments
syntax).

10
Multiple Constructors
public class Circle {
public double x,y,r; //instance variables
// Constructors
public Circle(double centreX, double cenreY, double radius) {
x = centreX; y = centreY; r = radius;
}
public Circle(double radius) { x=0; y=0; r = radius; }
public Circle() { x=0; y=0; r=1.0; }

//Methods to return circumference and area


public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}

11
class Complex
{
int real,imag;
//constructor overloading
Complex()
{
System.out.println("Welcome");
real=imag=0;
}
Complex(int real,int imag)
{
this.real=real;
this.imag=imag;
}

Java Programming 12
Complex(Complex c) //passing object as argument in constructor
{
real=c.real;
imag=c.imag;
}
void disp()
{
System.out.println(real +":"+imag);
}
public static void main(String a[])
{
Complex c1=new Complex();
c1.disp();
Complex c2=new Complex(100,200);
c2.disp();
c1=c2; // java supports assignment overload
c1.disp();
Complex c3=new Complex(c1);//copy cons
c3.disp();
}
}

Java Programming 13
Method Overloading
• Constructors all have the same name.
• Methods are distinguished by their signature:
– name
– number of arguments
– type of arguments
– position of arguments
• That means, a class can also have multiple usual
methods with the same name.

• Not to confuse with method overriding (coming up),


method overloading:

14
class Search
{
boolean search(int x,int a[])
{
for(int i=0;i<a.length;i++)
if(a[i] == x) return true;
return false;
}
boolean search(char x,char a[])
{
for(int i=0;i<a.length;i++)
if(a[i] == x) return true;
return false;
}

Java Programming 15
public static void main(String a[])
{
int x[]=new int[] {10,20,30,40,50};
char []y=new char[]{'a','b','c','d','e'};

Search s1=new Search();


if( s1.search(300,x) true)
System.out.println("Item is available");
else
System.out.println("Item is not available");

if(s1.search('x',y))
System.out.println("Item is available");
else
System.out.println("Item is not available");
}
}

Java Programming 16
Static Members
• Java supports definition of global methods and variables that
can be accessed without creating objects of a class. Such
members are called Static members.
• Define a variable by marking with the static methods.
• This feature is useful when we want to create a variable
common to all instances of a class.
• One of the most common example is to have a variable that
could keep a count of how many objects of a class have been
created.
• Note: Java creates only one copy for a static variable which
can be used even if the class is never instantiated.

17
Static Methods
• A class can have methods that are defined as static
(e.g., main method).
• Static methods can be accessed without using
objects. Also, there is NO need to create objects.
• They are prefixed with keyword “static”
• Static methods are generally used to group related
library functions that don’t depend on data members
of its class. For example, Math library functions.

18
class Static
{
static int x,y;
static void get()
{
x=100;y=20;
System.out.println(x +" " +y);
}
public static void main(String a[])
{
get();
}
}

Java Programming 19
Static methods restrictions
• They can only call other static methods.
• They can only access static data.
• They cannot refer to “this” or “super” (more
later) in anyway.

20
Inheritance in Java
• One of Cornerstones of OOP
• Allows hierarchical classifications of class
• A class that is inherited is called super class
• A class that does the inheriting is called sub
class
• A subclass is a specialized version of
superclass

Java Programming 21
Types
• Single Inheritance

• Multilevel Inheritance

• Multiple Inheritance – does not support


directly in Java ( with the help of interface)

• Hiearchical Inheritance

Java Programming 22
class A
Single Inheritance
{
int x;
A(int x) { this.x=x; }
void disp() {System.out.println(x);}
}
Output
class B extends A
{ ???
B( ) { System.out.println("Deri");}

public static void main(String a[])


{
A a1=new A( ); a1.disp();

A a2=new A(10); a2.disp();

B b=new B( );
}
}
Java Programming 23
Modified Code
class A
{
int x;
A( ) { System.out.println(“Base class”); }
A(int x) { this.x=x; }

void disp() {System.out.println(x); }


}
class B extends A
{
B( ) { System.out.println("Derived class");}

public static void main(String a[])


{
A a2=new A(10);
a2.disp();

B b=new B( );
}
}

Java Programming 24
super keyword in Java
• super ()

• super.varible name

• super.method name

• Note: Like ‘this’ keyword in C++

Java Programming 25
class base
Super() method
{
int x;
base( ) { x=5; }
}
class supercheck extends base
{
int b;
supercheck( )
{
super ( ); //should be written in first line
b=10;
System.out.println(x +"\t" + b);
}

public static void main(String a[])


{ supercheck s=new supercheck(); }
}

Java Programming 26
Super.method name
import java.io.*;
class Shape
{
int a;
void get()
{
try
{
DataInputStream d=new DataInputStream(System.in);
System.out.println("Enter shape value");
String s=d.readLine();
a=Integer.parseInt(s);
}catch(Exception e){}
}
}

Java Programming 27
class Rectangle extends Shape
{
int b, area;
void get() // method override
{
super.get(); // calling base class method.
try
{
DataInputStream d=new DataInputStream(System.in);
System.out.println("Enter Rectangle value");
String s=d.readLine();
b=Integer.parseInt(s);
}catch(Exception e){}
area=a*b;
}
public void disp() { System.out.println(area); }

public static void main(String a[])


{ Rectangle r=new Rectangle(); r.get(); r.disp(); }
}

Java Programming 28
Super.variable name
class base
{
int x;
base( ) { x=5; }
}
class supervar extends base
{
int x;
supervar( )
{
x=20;
super.x=10; // written anywhere in pgm
System.out.println(super.x +"\t" + x);
}
public static void main(String a[])
{ supervar s=new supervar(); }
}
Java Programming 29
Multilevel Inheritance
import java.io.*;
class Student
{
String name;
int rno;
Student() { name="\0"; rno=0; }
Student(String s,int r) { name=s; rno=r; }
void get()
{
try
{
System.out.println("Enter name");
DataInputStream d=new DataInputStream(System.in);
name=d.readLine();
System.out.println("Enter rollno");
d=new DataInputStream(System.in);
rno=Integer.parseInt(d.readLine());
}catch(Exception e){}
}
}
Java Programming 30
class Marks extends Student
{
int mark[]=new int[5];
Marks() { }
Marks(String s,int r,int[] m)
{
super(s,r);
for(int i=0;i<m.length;i++) mark[i]=m[i];
}
void getmarks()
{
get();
System.out.println("Enter marks");
try
{
DataInputStream d=new DataInputStream(System.in);
for(int i=0;i<5;i++)
mark[i]=Integer.parseInt(d.readLine());
}catch(Exception e){}
}
}

Java Programming 31
class Result extends Marks
{
int total;
Result() {total=0;}
Result(String s,int r,int[] m) { super(s,r,m); }
void result_disp() {
for(int i=0;i<5;i++) total += mark[i];
System.out.println(name + " " + rno + " " +total);
}
public static void main(String a[])
{
int[] x=new int[]{100,90,80,97,80};
Result r[]=new Result[2]; //array of objects
r[0]=new Result("Shanthi",10,x);
r[0].result_disp();
r[1]=new Result();
r[1].getmarks();
r[1].result_disp();
}
} Java Programming 32
Multiple Inheritance
• Java does not support multiple inheritance
directly like

Class B extends A, C ×
• Where A and C are base class of B

 By using interface it is possible

Java Programming 33
Interface
• It is defined like a class which have a general
form of methods in it.

• Interface can be used in class by using


‘implements’ keyword
• Eg.
interface inter { int x=100; void disp(); }
class A implements inter { ….. }

Java Programming 34
interface inter
{
int x=200;
void disp();
}
class A
{ void check() { System.out.println("Checking base class");} }

class interc extends A implements inter


{
public void disp()
{System.out.println(x);}
public static void main(String a[])
{ interc b=new interc(); b.disp(); b.check(); }
}

Java Programming 35
Multiple interfaces
interface i
{ int x=100; void disp(); }
interface j
{ int y=200; void dispj(); }

class intercheck implements i,j


{
public void disp() { System.out.println(x);}
public void dispj() { System.out.println(y);}

public static void main(String a[])


{ intercheck i=new intercheck();
i.disp(); i.dispj(); }
}
Java Programming 36
interface
interface i
extends interface
{ int x=100; void disp(); }

interface j extends i
{ int y=200; void dispj(); }
class intercheck implements j
{
public void disp() { System.out.println(x);}
public void dispj()
{ disp(); System.out.println(x+y); }
public static void main(String a[])
{
intercheck i=new intercheck();
i.disp(); i.dispj();
}
}
Java Programming 37
Abstract class
• Certain methods must be overridden by
subclasses by specifying ‘abstract’ modifier.

• ‘abstract’ keyword is specified in method which is


in superclass.

• A class which contains abstract method is called


as ‘abstract class’.

• An abstract class cannot be insantiated with new


keyword directly.

Java Programming 38
abstract class A
{
void check()
{ System.out.println("Ord meth"); }
abstract void disp();
}
class Abstract extends A
{
void disp() // should override abstract meth.
{ System.out.println("Hello"); }
public static void main(String a[])
{
Abstract a1=new Abstract ();
a1.disp();
// A a2=new A(); // can't create object
A a2=new Abstract(); // possible
a1.check();
a2.check();
}
}
Java Programming 39
Abstract and interface
• If an interface contains some methods and it
is implemented in one class, that class should
define all the methods in that interface

• Otherwise, that class should be declared as


abstract class

Java Programming 40
Abstract and interface
interface I { int x=100; void disp(); }
interface j extends I { int y=200; void dispj(); }
abstract class inter implements j
{
public void disp() { System.out.println(x); }
abstract void check( );
}
class intercheck extends inter
{
public void dispj() { System.out.println(y); }
void check() { System.out.println("Abstract method call"); }
public static void main(String a[])
{
intercheck i1=new intercheck();
i1.disp(); // abstract class method
i1.dispj(); // inteface j method
inter in=i1; // can assign obj to abstract class obj
in.disp(); in.dispj();
in.check(); // abstract method call
}
}

Java Programming 41
Final keyword
• Final variable - constant value

• Final method – cannot be override

• Final class – cannot be extended

Java Programming 42
Final variable
class check
{
final int x=10;
void disp()
{
x=20; // can’t change it
}
}

Java Programming 43
Final method
class A
{
final void disp() { System.out.println("Base"); }
}
class Finalmeth extends A
{
void disp() / /can't be override
{ System.out.println("Derived"); }

public static void main(String a[])


{
Finalmeth f=new Finalmeth();
f.disp();
}
}

Java Programming 44
Final class
final class A
{
void disp() { System.out.println("Base");}
}
class Finalmeth extends A // can't extend final class
{
public static void main(String a[])
{
Finalmeth f=new Finalmeth();
f.disp();
}
}

Java Programming 45
package
• Predefined package
import java.util.*;
import java.io.*;
import java.sql.*;
import java.applet.*;
import java.awt.event.*;

• User defined package

Java Programming 46
Main Inside Package Steps
• Working folder c:\jp>

1. create folder name as same name as package


name c:\jp\mypack
2. compile within that folder. c:\jp\mypack\javac
mainclass.java
3. go to previous parent folder. c:\jp\
4. run java packagename.classname c:\jp> java
mypack.mainclass

Java Programming 47
User defined package steps
1. create mypack folder
2. save the sample.java file in mypack folder
3. set classpath=.;pkg parent folder path

eg. c:\jp\mypack> set classpath=.;c:\jp


c:\jp\mypack> javac sample.java
c;\jp> java mypack.sample

Java Programming 48
Simple package
package mypack;
public class Base
{
public void disp()
{
System.out.println("Within package");

}
}

Java Programming 49
package mypack;
class sample
{
public static void main(String a[])
{
Base b=new Base();
b.disp();
}
}
Java Programming 50
Other type of package
package p1;
public class Base
{
private int a=10;
protected int b=20;
public int c=30;
int x=40;
public Base()
{
System.out.println(a+ " "+b +" " +c + " " +x); }
}

Java Programming 51
package p1;
public class Deri extends Base
{
public Deri()
{
System.out.println(b+ " " +c + " "+x);
}
}
Java Programming 52
package p1;
public class diff
{
public diff()
{
Base b=new Base();
System.out.println(b.b + " "+b.c+" " +b.x);
}
}
Java Programming 53
package p1;
class demop1
{
public static void main(String a[])
{
Base b=new Base();
Deri d=new Deri();
diff d1=new diff();
}
}

Java Programming 54
• If a package contains 4 classes
– Base class
– Derived class
– Non-derived class
– Main class
Then following way, we should run package

Java Programming 55
Running package
• Main inside package:

– C:\jp\p1> javac Base.java


– C:\jp\p1>javac Deri.java
– C:\jp\p1>set classpath=.;c:\jp

– C:\jp\p1>javac diff.java
– C:\jp\p1>javac demop1.java

Running : C:\jp>java p1.demop1

Java Programming 56
Main outside package:
set class and methods of class should be declared
as public
All Base, Deri and diff class should be declare as
public and their methods should also be declared
as public

Compiling: c:\jp>javac demop1.java

Running: c:\jp>java demop1

Java Programming 57
Main outside package
import p1.*;
class demop
{
public static void main(String a[])
{
Base b=new Base();
Deri d=new Deri();
diff d1=new diff();
}
}
..Save this file in c:\jp
..Set classpath as ;c:\jp;
..Run program as usual

Java Programming 58
Important Note in Package
important :
if main is inside package, run from its
parent directory as
java packname.filename

otherwise
set classpath then compile and run it.

Java Programming 59
Polymorphism
• Compile time polymorphism
• Method overloading

• Runtime polymorphism
• Method overriding
• Dynamic method dispatch

Java Programming 60
Method Overloading
• Same Method name
• Different parameter types
• same/Different return type
within a class

Java Programming 61
Concept
• Same Method name, parameter types, same
return type

• Used in Base class and Derived class

• How to Overcome???
#include<iostream.h>
#include<conio.h>

class a
{
public:
a() { cout<<"hi";}
a(int x){cout<<"Base hi";}
void get(){cout<<"Base"; }
};
class b :public a
{
public:
//b() {cout<<"bye";}
b(int y){cout<<"Derived Bye"; } // should be derived
void get(){cout<<"hello";}
};

void main()
{
clrscr(); a a1; b b1(10); b1.get(); getch();
}
Method Override
class base
{ int x;
base(int a) { x=a;}
void disp() { System.out.println(x);}
}
class override extends base
{
float y;
override(int x,float y) { super(x); y=124.57f; }
void disp(){ super.disp(); System.out.println(y);}

public static void main(String a[])


{
override o=new override(100,12.36f);
o.disp(); // derived class method is called
}
}

Java Programming 64
class base
Dynamic Method Dispatch
{ void disp() { System.out.println("Base");} }
class dynmeth extends base
{ void disp(){ System.out.println("Derived");}

public static void main(String a[])


{
base sample=new base();

base b=new base();


sample=b;
sample.disp(); // base class method

dynmeth d1=new dynmeth();


sample=d1;
sample.disp(); // derived class method
}
}
Java Programming 65
Why override?
• Java supports run-time polymorphism by
using overriding methods

• One interface multiple methods concept

• This dynamic runtime mechanism supports


code reusage and robustness

Java Programming 66
Exception Handling
• Predefined Exception
– NegativeArraySizeException
– NullPointerException
– StringIndexOutOfBoundsException
– Arithmetic Exception
– ArrayIndexOutofBounds Exception
– ……
• User defined Exception
– Extends Exception
Java Programming 67
import java.util.*; //Random class is in this package
class exception
{
public static void main(String arg[])
{
int a=10,b=0;
int x[]=new int[5];
Random r=new Random();
try
{
b=r.nextInt();
b=a/b;
}
catch(ArithmeticException ae )
{
System.out.println("Denominator should not be zero");
}
finally {
System.out.println("I am always working");
}
System.out.println(b);
}
}
Java Programming 68
Our Own Exception
class ourexcept extends Exception
{
private int a;
ourexcept(int aa)
{
a=aa;
}
public String toString()
{
return "Error";
}
static void compute(int a) throws ourexcept
{
if(a>10)
throw new ourexcept(a);
System.out.println(a);
}
Java Programming 69
public static void main(String ar[])
{
try
{
compute(2);
compute(11);
}
catch(ourexcept o)
{
System.out.println(o);
}
}

Java Programming 70
I/O Stream

Java Programming 71
import java.io.*;
File class
class fileclass
{
public static void main(String a[])
{
File f=new File("d:/subject/jp/pgms/unit-3/file.java");

System.out.println(f.getName() );
System.out.println( f.getPath());
System.out.println( f.getAbsolutePath());
System.out.println( f.getParent());
System.out.println( f.canWrite());
System.out.println( f.isDirectory());
System.out.println(f.lastModified() );
System.out.println(f.length() );
System.out.println( f.isHidden());
}
} Java Programming 72
File Directory
import java.io.*;
class fileclass {
public static void main(String a[]) {
String ss="d:/subject/jp/pgms";
File f1 = new File(ss);
if (f1.isDirectory()) {
System.out.println("Directory of " + ss);
String s[] = f1.list(); //list of files
for (int i=0; i < s.length; i++)
{
File f = new File(ss +"/" + s[i]);
if (f.isDirectory())
System.out.println(s[i] + " is a directory");
else
System.out.println(s[i] + " is a file");
}
}
else System.out.println(ss + " is not a directory");
}

Java Programming 73
Streams
An abstraction that produce or consumes information

Byte Stream used for read/writing binary data.


InputStream and OutputStream , ByteArrayInputStream , DataInputStream,
FileInputStream , FilterInputStream, InputStream
PipedInputStream

Character Stream used for i/o for characters.


Reader and Writer, BufferedReader, CharArrayReader
FileReader, FilterReader, InputStreamReader
PipedReader, Reader, StringReader

System -in,out,err
InputStreamReader in.
PrintStream out,err

Java Programming 74
import java.io.*; File Read
class file {
public static void main(String a[]) throws IOException {
int i;
FileInputStream fin;
try
{
fin=new FileInputStream(a[0]);
i=fin.read();
while(i!= -1) {
System.out.print((char)i);
i=fin.read(); }
fin.close();
} catch(FileNotFoundException fe)
{System.out.println("File Creation Error"); }
}
}
Java Programming 75
import java.io.*;
File Read & Write
class file{
public static void main(String a[]) throws IOException {
int i;
FileInputStream fin; FileOutputStream fout;

try {
fin=new FileInputStream(a[0]);
fout=new FileOutputStream("a.txt");

i=fin.read();
while(i!= -1)
{ fout.write(i); i=fin.read(); }
fin.close(); fout.close();
}catch(FileNotFoundException fe)
{ System.out.println("File Creation Error"); }
}
}

Java Programming 76
File Reader
• While the byte stream classes provide sufficient
functionality to handle any type of I/O operation.
• They cannot work directly with Unicode
characters.
• Since one of the main purposes of Java is to
support the “write once, run anywhere”.
• It was necessary to include direct I/O support for
characters.
• Top of the character stream hierarchies are the
Reader and Writer abstract classes.

Java Programming 77
File Reader
import java.io.*;
class filereader
{
public static void main(String args[]) throws Exception
{
FileReader fr = new FileReader("file.java");
FileWriter fw=new FileWriter("a.txt");

BufferedReader br = new BufferedReader(fr);


String s;
while((s = br.readLine()) != null)
{
System.out.println(s);
fw.write(s);
}
fr.close(); fw.close();
}
}
Java Programming 78
Word Count in File
import java.io.*;
class wordcount {
public static int words = 0; public static int lines = 0; public static int chars = 0;
public static void wc(InputStreamReader isr) throws IOException {
int c = 0;
while ((c = isr.read()) != -1) {
chars++;
if (c == '\n') { lines++; ++words; }
if(c==' ' || c=='\t' || c=='\r') ++words;
}
}
public static void main(String args[]) {
FileReader fr;
try {
if (args.length == 0)
wc(new InputStreamReader(System.in));
else
for (int i = 0; i < args.length; i++) {
fr = new FileReader(args[i]); wc(fr); }
}catch (IOException e) {return;}
System.out.println(lines + " " + words + " " + chars);
}
}
Java Programming 79
Object Cloning & Serialization
• Serialization is the process of writing the state of an object to a byte
stream. This is useful when you want to save the state of your program
to a persistent storage area,such as a file.

• Serialization is also needed to implement Remote Method Invocation


(RMI).

• RMI allows a Java object on one machine to invoke a method of a Java


object on a different machine.

• An object may be supplied as an argument to that remote method. The


sending machine serializes the object and transmits it. The receiving
machine deserializes it.

• If you attempt to serialize an object at the top of an object graph, all of


the other referenced objects are recursively located and serialized.

• Similarly, during the process of deserialization, all of these objects and


their references are correctly restored.
Java Programming 80
import java.io.*;
public class pending
{
public static void main(String args[])
{
try
{
MyClass object1 = new MyClass("Hello", -7, 2.7e10);
System.out.println("object1: " + object1);
FileOutputStream fos = new
FileOutputStream("serial");
ObjectOutputStream oos = new
ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
}catch(Exception e) {System.exit(0);}

Java Programming 81
// Object deserialization

try {
MyClass object2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass)ois.readObject();
ois.close();
System.out.println("object2: " + object2);
}catch(Exception e) { System.exit(0);}
}
}

Java Programming 82
class MyClass implements Serializable
{
String s; int i; double d;
public MyClass(String s, int i, double d)
{ this.s = s;
this.i = i;
this.d = d;
}
public String toString()
{ return "s=" + s + "; i=" + i + "; d=" + d; }
}

Java Programming 83
Threads
• Two or more parts that run concurrently in a
program is called Thread

• Methods
– getName,
– getPriority,
– isAlive
– join,
– run,
– sleep,
– start
Java Programming 84
Single Thread
class thread {
public static void main(String ar[]) {
Thread t=Thread.currentThread();
System.out.println(t.getName());
t.setName("Hi");

try {
for(int i=1;i<=10;i++)
{ System.out.println(i); Thread.sleep(1000); }
}catch(InterruptedException ie){}
System.out.println("Name of thread " + t.getName());
System.out.println("Priority " + t.getPriority());
System.out.println(t.isAlive());
}
}
Java Programming 85
Implementation
• Two Way implementation

– Implements Runnable interface

– Extends Thread class

Java Programming 86
Runnable interface
class sample implements Runnable {
Thread t;
sample()
{ t=new Thread(this,"checking"); t.start(); }
public void run()
{
try {
for(int i=1;i<=5;i++)
{ System.out.println("Child "+i);
Thread.sleep(1000);
}
}catch(InterruptedException ie) {}
}
}

Java Programming 87
class samplethread
{
public static void main(String a[])
{
sample s=new sample();
}
}

Java Programming 88
Thread extends
class sample extends Thread
{
sample()
{ super("checking"); start(); }
public void run()
{
try {
for(int i=1;i<=5;i++)
{
System.out.println("Child "+i);
Thread.sleep(1000);
}
}catch(InterruptedException ie) {}
System.out.println("Child");
}
}
Java Programming 89
class samplethread {
public static void main(String a[])
{
sample s=new sample();
}
}

Java Programming 90
MultiThread handling
class sample implements Runnable {
String name; Thread t;
sample(String s)
{ name=s; t=new Thread(this,"checking"); t.start(); }

public void run() {


try {
for(int i=1;i<=5;i++) {
System.out.println(name+i);
Thread.sleep(1000);
}
}catch(InterruptedException ie) {}
}
}
Java Programming 91
class multithread
{
public static void main(String a[])
{
new sample("one ");
new sample("two ");
new sample("three ");

try
{
for(int i=1;i<=5;i++)
{
System.out.println("Main " +i);
Thread.sleep(1000);
}
}catch(InterruptedException ie) {}
}
}

Java Programming 92
Synchronization
class sample implements Runnable
{
String name;
Thread t;

static void call1()


{
System.out.print("[");
try
{
System.out.print("hello");
Thread.sleep(1000);
}catch(InterruptedException ie){}
System.out.println("]");
}

Java Programming 93
sample(String s) {
name=s; t=new Thread(this,"checking");
t.start(); }
public void run() { call1(); }
}
class sync {
public static void main(String a[]) {
sample s1=new sample("one ");
sample s2=new sample("two ");
sample s3=new sample("three ");
try { s1.t.join(); s2.t.join(); s3.t.join();
}catch(InterruptedException ie) {}
}
}

Java Programming 94
Synchronized keyword
synchronized static void call1()
{
System.out.print("[");
try
{
System.out.print("hello");
Thread.sleep(1000);
}catch(InterruptedException ie){}
System.out.println("]");
}

Java Programming 95
Thank You

Queries
???

S-ar putea să vă placă și