Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
JAVA PROGRAMMING SUBJECT CLASS UNIT SEMESTER STAFF NASC –CS&IT : JAVA PROGRAMMING : III BSC CS : III : 6 : I.GOBI UNIT-III: Arrays, Strings and Vectors – Interfaces: Multiple Inheritance – Packages: Putting Classes together – Multithreaded Programming. ARRAYS `Array is a collection of values of the same data type referred by a common value. One-dimensional arrays The general form of one-dimensional array is type var-name[ ]; type is the data type of the each element that comprises the array. Ex – int marks[ ]; marks is a array variable, no array actually exists. The value of marks is set to null. A operator “new” is used to allocated space for an array. marks = new int[6]; marks refers to an array of 6 integers. The individual elements of the array can be accessed starting from the index or subscript 0. For Ex. class Student{ public static void main(String args[ ]){ int marks[ ] = new int[6]; marks[0] = 50; marks[1] = 55; marks[2] = 43; marks[3] = 61; marks[4] = 77; marks[5] = 58; System.out.println(“The marks scored in subject1 is :”+marks[0]); JAVA PROGRAMMING NASC –CS&IT } An array initializer is a list of comma separated expressions surrounded by curly braces. The commas separated the values of the array elements. The array will be created large enough to hold exactly the number of elements you specify in the array initializer. Java strictly checks that you don’t store or reference values outside the range of the array. Java runtime will check to be sure that all array indices are in the correct range. Multi- dimensional arrays These are arrays within arrays. The multidimensional arrays are allocated in blocks. If it is an X by Y by Z three-dimensional matrix, then the storage required will be X times Y times Z times the size of the type stored in each cell. In Java you can declare a variable to be three- dimensional but leave out the second and the thIrd dimension then allocate the Y and Z directions separately. Ex double matrix [ ] [ ] = new double [4] [4]; matrix[0] = new double[4]; matrix[1] = new double[4]; matrix[2] = new double[4]; matrix[3] = {0,1,2,3}; Ex class Exarray{ public static void main(String args[ ]){ int twodim = new int [4] [5]; int I, j, k = 0; for(i = 0; i < 4 ; i++ ){ for(j = 0 ; j<5; j++){ twodim[i][j] = k ; k++; } } for(i = 0; i < 4 ; i++ ){ for(j = 0 ; j<5; j++){ System.out.println( twodim[i][j] ) ; k++; } } } } STRING HANDLING CONSTRUCTORS String class is defined in java.lang package. The Format of string constructors are 1. String s = new String(); JAVA PROGRAMMING NASC –CS&IT 2. String (char chars [ ]); The first constructor is used when you need to create an empty string. To create a String initialized by an array of characters the second constructor can be used You can specify a subrange of a character array with the following constructor String (Char chars [ ], int startindex, int numchars); STRING CONCATENATION String concatenation can be done with the help of + operator and using the concat() method. public class Democoncat{ public static void main(String args [ ] ){ String s1 = “10” ; String s2 = “I have” + s1 +”copies of my certificate” ; System.out.println(s2); } } output : I have 10 copies of my cerificate String concatenation with other data types public class Democoncat{ public static void main(String args [ ] ){ int s1 = 10 ; String s2 = “I have” + s1 +”copies of my certificate” ; System.out.println(s2); } } In the above ex, the int value is concatenated with the string and we get the output as I have 10 copies of my certificate. Using concat() public class Democoncat{ public static void main(String args [ ] ){ String s1 = “concatenation” ; String s2 = “string” ; System.out.println(s2.concat(s1)); } JAVA PROGRAMMING NASC –CS&IT } The output is : string concatenation . CHARACTER EXTRACTION Methods for character extraction 1.charAt() This method is used to extract a single character directly from the a String. The form char charAt(int where) where is the index of the character which you want to get. This value must be non-negative. char ch; ch = “negative”.charAt(2); which will give the result as “g”. 2. getChars() This can be used when you need to extract more than one character at a time. The general form is void getChars(int sourceStart, int sourceEnd, char target [ ], int targetstart); sourceStart specifies the beginning index of the substring and sourceEnd specifies the index of the end of the substring. The character till the position sourceEnd – 1 will be in the substring. target [ ] is the name of the char array where your extracted characters or substring is placed and targetstart specifies the starting position of the array target [ ]. class getcharsDemo{ public static void main(String args [ ]){ String s = “This is a demo of the method”; int start = 10; int end = 4 ; char buf [ ] = new char[end – start ] ; s.getchars(start, end, buf , 0); System.out.println(buf); } } JAVA PROGRAMMING NASC –CS&IT The output is : demo 3. getBytes() This is an alternative to getChars() which stores characters in an array of bytes. It uses the default character-to-byte conversions by the platform. byte [ ] getBytes() ; STRING COMPARISION equals() method is used to compare two strings. The form is boolean equals(Object str) ; str is the string that is being compared with the invoking String object String s1 = “HAI” ; String s2 = “hai” ; String s3 -= “hai” ; s2.equals(s3) returns true but s1.equals(s2) returns false as Java is case-sensitive. we have another method equalsIgnoreCase(String str) for this. s1.equalsIgnoreCase(s2) returns true. == is used to compare object references. It returns true if both the object references refer to the same instance else they return false String s1 = “hello” String s2 = new String (s1); (s1==s2) returns false as s2 creates a new instance and the s1 and s2 doesn’t refer to the same copy of the instance. JAVA PROGRAMMING NASC –CS&IT INTERFACES Interfaces are similar to classes but they lack instance variables and their methods are declared without any body. So interfaces can be called as Pure abstract classes. Once defined any number of classes can implement an interface. And one class can implement any number of interfaces. Any class that implements an interface must provide definition for the complete set of methods in the interface. Interfaces are designed to support dynamic method resolution at runtime. Defining an Interface The general form of the interface is access interface name { return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname1 = value; ………………………………. } access can be either public or not defined. If not defined the default is package access(i.e the interface is available only to the members that belong to the same package as that of the interface). name is the name of the interface. The methods doesn’t have any body and they just end with a semicolon. These methods are abstract methods. Variables in the interface are final and static which means that their value cannot be changed by the implementing class. These variables must be initialized with a constant value. Ex - of an interface interface Callback{ void call(int param); } IMPLEMENTING INTERFACES To implement an interface include the implements clause in the class definition. access class classname [extends superclass] [ implements interface [, interface.]{ // class body } Ex – we will define a class that implements the above interface(Callback) class Sample implements Callback{ public void Call(int p){ System.out.println(“ method called with “ +p); JAVA PROGRAMMING NASC –CS&IT } } The above class Sample that implements the Callback interface can also have other methods and variables of its own. PARTIAL IMPLEMENTATIONS If a class that includes an interface doesn’t provide implementation for all the methods in the interface then that class must be declared as abstract. For ex abstract class Incomplete implements Callback{ int a, b ; void show() { System.out.println(a + “ “ + b); } } since the above class didn’t provide implementation for the method call in the interface Callback, this class has been declared as abstract. INTERFACES CAN BE EXTENDED One interface can inherit another using the keyword extends. When a class implements an interface that inherits another interface, it must provide implementations for all the methods defined in the interface chain. interface A { void meth1(); void meth2(); } interface B{ void meth3(); } class Myclass implements B{ public void meth1(){ System.out.println(“implement meth1”); } public void meth2(){ System.out.println(“implement meth2”); } public void meth3(){ System.out.println(“implement meth3”); } JAVA PROGRAMMING NASC –CS&IT } Since Myclass implements the interface B it has to provide implementation for the method in B as well as the for the methods of the interface A which B inherits. INHERITANCE Defining a new class based on an existing class is called derivation. The new class or derived class is called as the direct subclass of the class from which it is being derived. The original class is called as the base class as it forms the base for the definition of the derived class. The base class can also be called as super class. The inclusion of members of a base class in a derived class so that they are accessible in the derived class is called class Inheritance. If a base class member is not accessible in a derived class, then it is not an inherited member of the derived class. Objects of the derived class type will contain all the inherited members of the base class – both fields and methods Let us see a simple example for inheritance. A Son may have certain characteristics resembling his Father. In addition to that he will have his unique features. So we can say that the Son has derived certain features from his father which implies that Son can be called as a subclass of the superclass Father. The general declaration for a class that inherits a superclass is class subclass-name extends superclass-name{ body of the class } Java doesn’t support multiple inheritance. It only supports multi-level inheritance. So we can specify only one super class for any sub class we create. With multi-level inheritance, we can create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass. class Shape { int d1; int d2; public void setvalues(int dimen1, int dimen2 ){ d1 = dimen1; JAVA PROGRAMMING NASC –CS&IT d2 = dimen2; } } class Triangle extends Shape { int ar ; public void area(){ ar = (d1 * d2 )/ 2; System.out.println("Area of triangle:"+ar); } } class Rectangle extends Shape{ int ar; public void area(){ ar = d1* d2; System.out.println("Area of rectangle :"+ar); } } public class Inher{ public static void main(String args [ ]){ Triangle t = new Triangle(); t.setvalues(10,10); Rectangle r = new Rectangle(); r.setvalues(5, 10); t.area(); r.area(); } } We have defined a class Shape and we have assigned the dimensions. The two subclass inherited from Shape are Rectangle and Triangle. We have a method setvalues() in the base class which can be used to assign the dimensions. This base class method is inherited in both the subclasses. ie We have invoked the same method with reference to the object of Triangle, where we pass the values for base and height. And in the case of rectangle the values for breadth and height are passed . USING Super There will be times when you want to create a superclass that keeps the details of its implementation to itself In that case, there is no way for the subclass to directly access or initialize the variables on its own. Java provides the way for the subclass to refer its immediate superclass by using the keyword super super has 2 forms JAVA PROGRAMMING NASC –CS&IT 1. To access the superclass’s constructor 2. To access the member of a superclass To access superclass constructor A subclass can access the superclass constructor with the following syntax, super(parameter-list); parameter-list specifies any parameters needed by the constructor in the superclass super() must be the fist statement executed inside a subclass’s constructor. class Shape { int length; int breadth; Shape(int dimen1, int dimen2 ){ length = dimen1; breadth = dimen2; } } class Cuboid extends Shape { int height; Cuboid(int dimen1, int dimen2, int dimen3){ super(dimen1, dimen2); height = dimen3; } public int volume(){ return( length *breadth* height ); } } public class Shvolume{ public static void main(String args [ ]){ Cuboid c = new Cuboid(6, 8 ,7); System.out.println(“the volume of cuboid :”+c.volume()); } } In the above example we have initialized the values for dimensions1 and 2 in the constructor of superclass Shape. And the subclass Cuboid needs one more dimension to calculate its volume which we have initialized in its constructor. The superclass’s constructor is called inside the constructor of the subclass with the keyword super(); JAVA PROGRAMMING NASC –CS&IT To access a superclass member The general form is : super.member member can be a method or a instance variable. class Univexam{ int marks; } class Internal extends Univexam { int marks; Internal(int a, int b){ super.marks = a; marks = b; } void obtained() { System.out.println(“marks in university exam“ +super.marks); System.out.println(“marks in internal exam“ +marks); System.out.println(“Total marks obtained”+(super.marks+marks)); } } class Usesuper{ public static void main(String args[ ]){ Internal iobj = new Internal(40, 18); iobj.obtained(); } } In the above example we have used the same name marks for specifying the internal as well as the external marks. So there is a name collision between the variable in the super class and the sub class. Hence, the instance variable marks in the super class Univexam can be accessed in the subclass with the keyword super. ie super.marks, and the instance variable marks in class Internal can be accessed directly as marks. MULTI – LEVEL HIERARCHY As we know Java supports only multi-level hierarchy and not multiple inheritance. For ex, consider three classes A, B and C. ie It is not possible to declare as follows class A { datatype var1; JAVA PROGRAMMING NASC –CS&IT datatype var2; returntype method1(list of parameters){ body of method } } class B { datatype var1; datatype var2; returntype method1(list of parameters){ body of method } } class C extends A,B{ datatype var1; datatype var2; returntype method1(list of parameters){ body of method } } The above declaration is multiple inheritance of classes and is not supported by Java MULTI-LEVEL INHERITANCE class A { datatype var1; datatype var2; returntype method1(list of parameters){ body of method } } class B extends A{ datatype var1; datatype var2; returntype method1(list of parameters){ JAVA PROGRAMMING NASC –CS&IT body of method } } class C extends B{ datatype var1; datatype var2; returntype method1(list of parameters){ body of method } } This declaration is multi-level inheritance .Like, class A is the super class of B and class B is the super class of class C. So class B can access the members of A, and class C can access the members of B(of course only the public and protected members), which means that class C can access the members of A Example for multi-level inheritance class Box{ double width; double height; double depth; Box (double w, double h, double d){ width = w; height = h; depth = d; } public double vol(){ return (width * height * depth); } } class Boxweight extends Box{ double weight; Boxweight(double w, double h, double d, double m){ super(w, h, d); weight = m; } } class Shipment extends Boxweight{ double cost; Boxweight(double w, double h, double d, double m, double c){ super(w, h, d, m); JAVA PROGRAMMING NASC –CS&IT cost = c; } } public class Boxex{ public static void main(String args [ ] ){ Shipment s1 = new Shipment(10, 6, 8, 14, 20); Shipment s2 = new Shipment(9, 8,7,12, 10); System.out.println(“Volume of box1"+s1.vol()); System.out.println(“Volume of box2: “ +s2.vol()); } } METHOD OVERRIDING When a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.. When an overridden method is called within a subclass it will always refer to the version of the method defined by the subclass. The version of the method defined by the superclass will be hidden. class A { int i, j; A(int a, int b){ i = a; j = b; } void show(){ System.out.println(“ values of i and j : +i + “ “ +j ); } } class B extends A{ int k; B(int a, int b, int c){ super(a, b); k = c; } void show(){ System.out.println(“value of k:”+k); } } class Override{ public static void main(String args[ ]){ B ob1 = new B(); Ob1.show(); JAVA PROGRAMMING NASC –CS&IT } } When show() is invoked on an object of class B, the version of show() defined within B is used. This show() method in B overrides the show() in A. DYNAMIC METHOD DISPATCH Dynamic method dispatch is the way through which Java implements run-time polymorphism . Dynamic method dispatch is the mechanism by which a call to an overridden function is resolved at run-time rather than compile time.When an overridden method is called through a superclass reference, Java determines which version of that method to execute depending on the type of object referred to. This determination is made at runtime. When different types of objects are referred to, different versions of an overridden method will be called. We can say it is the type of object being referred to that determines which version of an overridden method will be executed. class A{ void callme(){ System.out.println(“Inside A ‘s callme method”); } } class B extends A{ void callme(){ System.out.println(“Inside B’s callme method”); } } class C extends A{ void callme(){ System.out.println(“Inside C’s callme method”); } } class Dispatch{ public static void main(String args [ ]){ A a = new A(); B b = new B(); C c = new C(); A r; r = a; r.callme(); r = b; r.callme(); JAVA PROGRAMMING NASC –CS&IT r = c; r.callme(); } } subclasses B and C override callme() declared in A. A reference of type A, called r is declared. The version of callme() is executed is determined by the type of object being referred to at the time of the call. ABSTRACT CLASSES Sometimes we will create a class without giving implementation for all methods. For ex- let us consider the example Shape. class Shape { int d1; int d2; public void setvalues(int dimen1, int dimen2 ){ d1 = dimen1; d2 = dimen2; } public void area(){ System.out.println(“Area not defined”); } } class Triangle extends Shape { int ar ; public void area(){ ar = (d1 * d2 )/ 2; System.out.println("Area of triangle:"+ar); } } class Rectangle extends Shape{ int ar; public void area(){ ar = d1* d2; System.out.println("Area of rectangle :"+ar); } } public class Inher{ public static void main(String args [ ]){ JAVA PROGRAMMING NASC –CS&IT Shape s = new Shape(); Triangle t = new Triangle(); t.setvalues(10,10); Rectangle r = new Rectangle(); r.setvalues(5, 10); t.area(); r.area(); } } In the superclass Shape there is no need to give the implementation for the method area() because it is not meaningful. Only in the subclasses we have a meaningful implementation by calculating the areas of the corresponding to the shapes triangle and rectangle. We can avoid the message in the body of the method area() inside the superclass Shape. When a method doesn’t have any implementation for its method, it is said to be an abstract method. It is declared using the abstract modifier along with the name of the method . And a class which has one or more abstract method is called as a abstract class. Since an abstract class is not concrete class, we cannot instantiate that class.(i.e it is not possible to create an instance of an abstract class). We say a class as concrete or complete only if that class has got implementation for all the methods in it. But since the abstract class doesn’t provide implementation for one or more methods it is not complete and hence we cannot create object of that class. We need to override those abstract methods in the subclasses and we can invoke those methods by creating instances of the subclasses. To declare a abstract method, the syntax is abstract return-type methodname(list of parameters); We will implement the above example with the use of abstract class which will make you clear the concept of abstract classes abstract class Shape { int d1; int d2; public void setvalues(int dimen1, int dimen2 ){ d1 = dimen1; d2 = dimen2; } abstract void area(); JAVA PROGRAMMING NASC –CS&IT } class Triangle extends Shape { int ar ; public void area(){ ar = (d1 * d2 )/ 2; System.out.println("Area of triangle:"+ar); } } class Rectangle extends Shape{ int ar; public void area(){ ar = d1* d2; System.out.println("Area of rectangle :"+ar); } } public class Inher{ public static void main(String args [ ]){ // Shape s = new Shape() ; illegal as we cannot instantiate an abstract class Triangle t = new Triangle(); t.setvalues(10,10); Rectangle r = new Rectangle(); r.setvalues(5, 10); t.area(); r.area(); } } Since the method area in superclass Shape doesn’t have any implementation, we have declared it as abstract.The class is declared abstract as it has got an abstract method. STATIC As we know, a class member can be accessed in conjuction with an object. If we want to access a member of the class we need to declare that member preceding with the access modifier static. At this point of time, we would remember the use of static keyword in the main() method. As main() method can be accessed even before creating any instance, we call it as a class method and to specify this we used the keyword static. Variables can also be declared as static, and when objects of the class is created, no copy of the static variable is made. And all instances share the same static variable. JAVA PROGRAMMING NASC –CS&IT Static variables have certain restrictions 1. They can only call other static methods 2. They must only access static data 3. They cannot refer to this or super in any way. Ex – class Usestatic{ static int a = 3; static double b ; static void Sqroot(){ System.out.println(“value of a:” +a); System.out.println(“Square root of a:” +b); } static{ System.out.println(“Static block”); b = Math.sqrt(a); } public static void main(String args [ ]){ Sqroot(); } } When a class is loaded, all the static statements are executed first. In the example, first a is initialized to 3, then the static block executes. ie the static block consists of the statement that calculates the square root of a. This static block ie is called as static initializer. Then the main method invokes the method Sqroot(). The println statements refer to the static variables a and b . If we want to access the static members of the class outside it, then we have to refer to the members as follows classname.method(); classname.variable; ie the classname followed by dot operator and the member . class Usestatic{ static int a = 3; static double b ; static void Sqroot(){ System.out.println(“value of a:” +a); System.out.println(“Square root of a:” +b); JAVA PROGRAMMING NASC –CS&IT } static{ System.out.println(“Static block”); b = Math.sqrt(a); } } public class Statex{ public static void main(String args [ ]){ Usestatic.Sqroot(); } } Final When variables are declared with the access modifier final, its value cannot be changed. final int a = 3; the value of a remains constant and it cannot be modified as it has been declared as final. Other uses of final keyword 1. With methods to prevent method overriding 2. With classes to prevent inheritance Methods can also be declared as final. In that case these methods cannot be overridden. So when we want to avoid certain methods from being overridden we can declare them as final. Methods declared as final can sometimes provide a performance enhancement. The compiler is free to inline calls because it knows they will not be overridden by a subclass. Since final methods cannot be overridden, a call to such a method can be resolved at compile time . This is called as early binding. Whereas when methods are overridden , a call to such method is resolved only at runtime which is called as late binding.(ie dynamic method dispatch) Use of final modifier in a class prevent it from being inherited. final class A{ int a = 10; void display(){ System.out.println(“value of a”+a); JAVA PROGRAMMING NASC –CS&IT } } class B extends A{ --------------------} // not possible as class A us declared as final When a class is declared as final by default all the methods in that class are final. So the methods inside a final class cannot be overridden. PACKAGES Packages are containers for classes that are used to keep the class namespace compartmentalized. Packages are stored in a hierarchical manner and are explicitly imported in to a new class definition A Java source file may contain any one or all of the following four internal parts 1. 2. 3. 4. A single package statement Any number of import statements A single public class declaration Any number of classes private to the package Consider a programmer has given a name “Sample” for the class he defines. If you define a class with the same name “Sample” a name collision occurs. You can avoid this name collision by defining your class Sample within a different package. So you can access the class within your package by specifying packagename.Sample. So the class inside your package is not accessible outside your package. Only the class members in the same package can access the class. DEFINING A PACKAGE To create a package, include package command as the first statement in your program followed by the package name. package pkg ; Where pkg is the name of the package. Any classes inside the file belong to the specified package. Java uses file system directories to store packages. i. e if you have a package say package Mypackage ; JAVA PROGRAMMING NASC –CS&IT All the . class files for the classes you describe in Mypackage must be stored in a directory called Mypackage. There can be any number of files with the same package statement. You can also create a hierarchy of packages i.e package pkg1[.pkg2] [. pkg3] ; We can’t rename a package without renaming the directory in which the classes are stored. CLASSPATH Consider that you create a class called Sinterest in a package called Myspace. Since the directory name has to match with your package, create a directory by name Myspace and put Sinterest.java in that directory and compile the file. The class file Sinterest.class will be in the directory in the Myspace directory. To make this work, you have two ways 1. You can go one hierarchy up by one level and try it as java Myspace.Interest or 2. You can set the Classpath as ; c:\Myspace; c:\java\classes ExPackage Myspace; public class Interest{ int n; float p ; float v; public Interest(int n, float p, float r){ this.n = n; this.p = p; this.r = r; } public void calculate(){ System.out.println(“Interest”+(n*p*r)); } } IMPORTING PACKAGES If you want to access a member of a class in a package, you need to specify the packagename.classname. Sometimes if a class belongs to a multilevel hierarchical package you need to type all the packages for every class you need to use. You can avoid this by using import statement. In the java source file, the import statement occurs immediately following the package statements and before any class definitions. The general form is import pkg1.pkg2.(classname/*); JAVA PROGRAMMING NASC –CS&IT You can either specify a explicit classname or a star which indicates that the system should import the entire package. For ex, we will use our Class Interest, which belongs to Myspace package. import Myspace ; public class Intdemo{ public static void main(String args[ ]){ Interest i = new Interest(4, 500, 2); i.calculate(); } } This example accesses the members of the class Interest in the package Myspace. So the package has to be imported before its class members are used. MULTI-THREADING In a multi-threading program we can execute more than one parts simultaneously. Each part of the program is called as a thread. Multithreading is a form of multitasking There are two forms of multi-threading. 1. Process-based multitasking 2. Thread-based multitasking Process based multitasking allows to run two or more programs concurrently. Process-based Program is the smallest unit Thread-based Thread is the smallest unit of dispatchable code of dispatchable code Processes are heavyweight tasks Threads are lightweight and requires same and requires separate address address space. space Interprocess communication Interthread communication is inexpensive is expensive Context switching between programs is expensive Ex – we can run a compiler Context switching between threads is inexpensive Ex - We can format text as well as print it JAVA PROGRAMMING as open a notepad as well NASC –CS&IT provided each task is described as a separate thread. JAVA THREAD MODEL In single-threaded systems, when a thread blocks because it is waiting for some resource, the entire program stops running, This wastes CPU time. This drawback is overcome by multithreading. Here one thread can pause without stopping other parts of your program. The idle time can be utilized somewhere else. So when a thread blocks a Java program, only the single thread that is blocked pauses. All other threads continue to run. Thread states Running Sleep Blocked Suspend Ready Any number of threads can be in the ready state, whereas only one thread can be in the running state at a time. When a thread waits for some resources it is said to be in the blocked state. The thread is said to be in sleep state if it is idle. One thread can suspend other thread’s activity which can be resumed later. Thread class and Runnable interface Java’s multithreading system is built upon the Thread class and the interface Runnable. The various methods defined by Thread class are method Description getName Obtain thread’s name getPriority Obtain thread’s priority isAlive To see if a thread is still running join Wait for a thread to terminate run Entry point for thread sleep Suspend a thread’s activity for a period of time JAVA PROGRAMMING start NASC –CS&IT Start a thread by calling its run method The Main thread When a Java program starts one thread begins execution automatically . It is called the main thread of the program . It is the last thread to finish execution. class CurrentThreadDemo{ public static void main(String args [ ]){ Thread t = Thread.currentThread(); System.out.println(“Current thread :” +t); t.setName(“My thread”); System.out.println(“After name Change: “ + t); try{ for (int i = 5 ; i > 0 ; i-- ){ System.out.println(i); Thread.sleep(1000); } }catch(InterruptedException e){ System.out.println(“Main thread interrupted”); } } } A reference to the current thread can be obtained by the method currentThread(). The default name for the thread is main and after name change it becomes My Thread. Creating a thread You can create a thread by instantiating an object of type Thread. It can be done by 2 ways 1. Extend Thread class 2. Implement Runnable interface class NewThread implements Runnable { Thread t ; NewThread() { t = new Thread(this, “Demo thread”); System.out.println(“Child thread “ + t); t.start() ; } public void run(){ JAVA PROGRAMMING NASC –CS&IT try { for(int i = 5 ; i > 0 ; i -- ) { System.out.println(“Child thread :” + i) ; Thread.sleep(500); } }catch(InterruptedException e){ System.out.println(“Child thread interrupted “); } System.out.println(“child thread exit”); } } public class ThreadDemo { pubic static void main(String args [ ]){ new NewThread(); try { for(int i = 5 ; i > 0 ; i -- ) { System.out.println(“Main thread :” + i) ; Thread.sleep(1000); } }catch(InterruptedException e){ System.out.println(“Main thread interrupted “); } System.out.println(“Main thread exit”); } } The NewThread’s constructor call the start method which is the starting point of execution. The main thread is the first thread to execute and it prints the value of i. The main thread then sleeps for 1 sec(1000 milliseconds) . And this idle time of 1 second is utilized by the child thread which displays the value of i. Since the child thread sleeps one half of a second it prints 2 values of in the interval of 1 second of the main thread’s sleeping time. The output will be Main thread : 5 Child thread : 5 Child thread : 4 Main thread : 4 Child thread : 3 Child thread : 2 Main thread : 3 Child thread : 1 Child thread Exit JAVA PROGRAMMING NASC –CS&IT Main thread : 2 Main thread : 1 Main thread Exit THREAD PRIORITIES Thread priority is used to decide when to switch between one running thread and another. This is called as Context switch . The following rules determine when a context switch takes place. 1. A thread can voluntarily give-up control 2. A thread can be pre-empted by a higher-priority thread To set a thread’s priority use the method final void setPriority(int level) ; level specifies the value for priority. It must be in the range of MIN_PRIORITY to MAX_PRIORITY. The corresponding values are 1 and 10 respectively. And the default priority is 5 which can be specified as NORM_PRIORITY SYNCHRONIZATION When two or more threads need to access a shared resource, they need some way to ensure that only one thread access the resource at a time. The process by which this is achieved is called as synchronization. Synchronization uses the concept of monitor(semaphore). Only one thread can own a monitor at a time. All other threads must wait for the monitor until the thread leaves the monitor. Using synchronized methods class Callme{ void call(String msg){ System.out.println(msg); try { Thread.sleep(1000); }catch(InterruptedException e){ System.out.println(“Interrupted”); } } } class Caller implements Runnable { String msg ; Callme target ; Thread t ; public Caller(Callme targ , String s ){ JAVA PROGRAMMING NASC –CS&IT target = targ ; msg = s ; t = new Thread(this); t.start(); } public void run(){ target.call(msg); } } class Synch{ public static void main(String args [ ]){ Callme target = new Callme(); Caller ob1 = new Caller(target , “Hello”); Caller ob2 = new Caller(target , “Synchronised”); } } In this program nothing stops the 2 threads from calling the same method on the same object at the same time. This is known as race condition as all the threads are racing to complete the method. To avoid this precede the method definition call with the keyword synchronized class Callme{ synchronized void call(String msg){ …… } } SYNCHRONIZED STATEMENT Though creating synchronized methods is an easy way of achieving synchronization it will not work in all cases. When you are using a class which is created by someone, you may not be able to access the source code and you can’t add synchronized keyword to the methods. The solution to this is you can put calls to the methods that are defined by the class inside a synchronized block. The general form of the statement is synchronized(object){ statements to be synchronized } Ex – class Callme{ void call(String msg){ JAVA PROGRAMMING NASC –CS&IT System.out.println(msg); try { Thread.sleep(1000); }catch(InterruptedException e){ System.out.println(“Interrupted”); } } } class Caller implements Runnable { String msg ; Callme target ; Thread t ; public Caller(Callme targ , String s ){ target = targ ; msg = s ; t = new Thread(this); t.start(); } public void run(){ synchronized(target) { // the method target is called with a synchronized block target.call(msg); } } } class Synch{ public static void main(String args [ ]){ Callme target = new Callme(); Caller ob1 = new Caller(target , “Hello”); Caller ob2 = new Caller(target , “Synchronized”); } } DEADLOCK Deadlock occurs when two threads have a circular dependency on a pair of synchronized objects. Suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread X tries to call any synchronized method in Y it will block as expected. If the thread in Y tries to call any synchronized method in X then then the thread waits forever. Deadlock is difficult to debug for 2 reasons 1. It occurs when the two threads time-slice. 2. It involve more than two threads and two synchronized objects. JAVA PROGRAMMING NASC –CS&IT Ex - create 2 classes A and B with methods foo() and bar() which pause before trying to call a method in the other class. The main class named Deadlock, creates and instance of A and B and then starts a second thread to set up the deadlock condition. The foo() and bar() methods use sleep() as a way to force the deadlock condition occur. class A{ synchronized void foo(B b){ String name = Thread.currentThread().getName(); System.out.println(name +” entered A.foo()); try { Thread.sleep(1000); }catch(Exception e){ System.out.println(“A interrupted”); } System.out.println(name +”trying to call B.last()”); b.last(); } synchronized void last(){ System.out.println(“Inside A.last); } } class B{ synchronized void bar(A a){ String name = Thread.currentThread().getName(); System.out.println(name +” entered B.bar()); try { Thread.sleep(1000); }catch(Exception e){ System.out.println(“B interrupted”); } System.out.println(name +”trying to call A.last()”); a.last(); } synchronized void last(){ System.out.println(“Inside B.last); } } class Deadlock implements Runnable{ A a = new A(); B b = new B(); Deadlock(){ JAVA PROGRAMMING NASC –CS&IT Thread.currentThread().setName(“Mainthread”); Thread t = new Thread(this, “racing thread”); t.start(); a.foo(b); System.out.println(“Back in main thread”); } public void run(){ b.bar(a); System.out.println(“Back in other thread”); } public static void main(String args [ ]){ new Deadlock(); } } THREAD API SUMMARY currentThread() This method returns the thread object which is the currently running thread yield() It causes the runtime to context switch from the current running thread to the next available runnable thread. This is the only way to ensure that threads at lower priority do not get starved. sleep(int n) This method causes the run-time to put the current thread to sleep for some milliseconds. After n milliseconds is expired, this thread will eligible to run again. Instance methods start() This method is to create a system thread and start its running. run() method on this thread’s target will be called in the new thread context. The start method cannot be called more than once on a given thread object run() This is the body of the running thread. It is called by the start method after the thread has been initialized. whenever the run method returns the current thread will stop. stop() JAVA PROGRAMMING NASC –CS&IT this causes the thread to stop immediately. This is an abrupt way to end a thread suspend() It stops running of thread without destroying the underlying system thread. If a thread is suspended, you can call resume() on the same thread to cause it to start running again. resume() It is used to revive a suspended thread setPriority(int p) Sets the thread’s priority to the value passed in. getPriority() Returns the thread’s current priority setName(String name) Used to give a name for the thread getName() Returns the current string value of the thread’s name.