Java Unit III Notes
Java Unit III Notes
JAVA
UNIT III
Prepared by
[Link]
Assistant Professor
PG & Research Department of Computer Science & Data
Analytics
Tiruppur Kumaran College for Women – Tirupur.
UNIT– III
Arrays, Strings and Vectors – Interfaces: Multiple Inheritance – Packages:
Putting Classes together – Multithreaded Programming.
ARRAYS
INTRODUCTION
An array is a group of contiguous or related data items that share a common name.
example Salary [10], represents the salary of 10 th employee. While the complete set of
values is referred to as an array, the individual values are called elements. Array can be
of any variable type.
One-dimensional Arrays
A list of items can be given one variable name using only one subscript and such a
variable is called a single subscripted or a one dimensional array. In mathematics, we
often deal with variables that are single subscripted. For instance, we use the equation, to
calculate the average of n values of x. In java, single subscripted variable x1 can be
expressed as
x[1],x[2],x[3]............................x[n].
For example, if we want to represent a setof five numbers, say(35, 40, 20, 57, 19), by an
array variable number as follows
Int number[]=new int [5];
And the computer reserves five storage locations as shown below:
number[0]
number[1]
number[2]
number[3]
number[4]
number[1] 40
20
number[2]
number[3] 57
number[4] 19
Creating an Array
Like any other variables, arrays must be declared and created in the computer memory
before they are used. Creation of an array involves three steps:
1. Declaring the array
2. Creating memory locations
3. Putting values into the memory locations.
Declaration of Arrays
Arrays in java may be declared in two forms:
For
typearrayname[];
m1
:
For type[]arrayname;
m2
:
Example:
Int number[ ];
float[] marks;
Creation of
Arrays
After declaring an array we need to create it in the memory. Java allows us to create arrays
using new operator only, as shown below:
Statement Result
points nowhere
number=new int[5];
number
Initialization of arrays
The final step is to put values into the array created. This process is known as initialization.
This is done using the array subscribes as shown below:
Example: number[2]=20;
number[0]=35; number[3]=57;
number[1]=4 number[4]=19;
0;
arrayname[sub
script]=
value;
Note that java creates arrays starting with subscript of 0 and end with a value one less than
the size specified. We can also initialize arrays automatically like,
Output:
Givenlist:5540806571
Sortedlist:8071655540
Output:
[A,E,I,O,U]
Two-dimensional Arrays
So far we have discussed the array variables that can store a list of values. There will be
Situations where a table of values will have to be stored. Consider the following data
table, which shows the value of sales for three items by four salesgirls:
i it it
e
m
2
sales 3 2 3
girl 7
#1 5
sales 2 1 3
girl 9
#2 0
sales 4 2 2
girl 3
#3 5
sales 2 3 3
girl 0
#4 0
Two-dimensional arrays are stored in memory as shown in figure. As with the single
dimensional arrays, each dimension of the array is indexed from zero to its maximum
size minus one; the first index selects the row and the second index select the column
within that row.
Example:
int myArray[ ][ ];
myArray=new int[3]
[4];
(or)int myArray[][]=new[3][4];
Output:
These statements create a two dimensional array as having different lengths for each
row.
STRINGS
String manipulation is the most common part of many Java programs. Strings represent a
sequence of characters. The easiest way to represent a sequence of characters in Java is
by using a character array.
Example:
char charArray[]=new char[4];
charArray[0]=' J ';
charArray[1]=' a ';
charArray[2]=' v ';
charArray[3]=' a ';
Although character arrays have the advantage of being able to query their length, they
themselves are not good enough to support the range of operations we may like to
perform on strings.
In Java, strings are class objects and implemented using two classes, namely, String and
StringBuffer. A Java string is an instantiated object of the String class. Strings may be
declared and created as follows:
Example:
String firstName;
firstName=newString("Anil");
String Arrays
String itemArray[]=new String[3];
Will create an itemArray of size 3 to hold three string constants.
String Methods
The String class defines a number of methods that allow accomplishing a variety of string
manipulation tasks. Some of the most commonly used string methods are:
1. s2=[Link]; [Link]()
2. s2=[Link]; [Link](s2)
3. s2=[Link](‗X‘,‘Y‘); 9. [Link](s2)
4. s2=[Link](); [Link](‗X‘)
5. [Link](s2) [Link](n)
6. [Link]() [Link](n,m)
Command Description
"Testing".equals(text1); Return true if text1 is equal to "Testing". The
check is case-sensitive.
"Testing".equalsIgnoreC Return true if text1 is equal to "Testing". The
ase(text1); check is not case-sensitive. For example, it
would also be true for "testing".
StringBuffer str1 = new Define a new String with a variable length.
StringBuffer();
[Link](1); Return the character at position 1. (Note: strings
are arrays of chars starting with 0)
[Link](1); Removes the first characters.
[Link](1, 5); Gets the substring from the second to the fifth
character.
[Link]("Test") Look for the String "Test" in String str. Returns
the index of the first occurrence of the
specified string.
[Link]("ing") Returns the index of the last occurrence of the
specified String "ing" in the String str.
StringBuffer does not support this method.
Hence first convert the StringBuffer to String
via method toString.
[Link]("ing") Returns true if str ends with String "ing"
[Link]("Test") Returns true if String str starts with String
"Test".
[Link]() Removes leading and trailing spaces.
[Link](str1, str2) Replaces all occurrences of str1 by str2
[Link](str1); Concatenates str1 at the end of str2.
[Link]() / Converts the string to lower- or uppercase
[Link]()
str1 + str2 Concatenate str1 and str2
String[] array = Splits the character separated myString into an
[Link]("-"); array of strings. Attention: the split string is a
String[]array2=myStrin regular expression, so if you using special
[Link]("\\."); characters which have a meaning in regular
expressions, you need to quote them. In the
second example the . is used and must be
quoted by two backslashes.
Output:
Is array 1 equal to array 2??
true
Isarray1equaltoarray3??
false
Output:
-32
0
0
Sample program to perform string concatenation:
public class JavaStringConcat
{
public static void main(String args[])
{
String str1 = "Hello";
Stringstr2="World";
//1. Using + operator
Stringstr3=str1+str2;
[Link]("String concat using+operator:"+str3);
//[Link]()method
String str4 = [Link](str2);
[Link]("String concat using String concat method:"+str4);
//[Link]
String str5 = new StringBuffer().append(str1).append(str2).toString();
[Link]("StringconcatusingStringBufferappendmethod:"+str5);
}
}
Output:
String concat using +operator:HelloWorld
String concat using String concat method:HelloWorld
String concat using String Buffer append method:HelloWorld
Output:
one two
three one
two three
one two
three
Sampleprogramtotrimastring :
publicclassRemoveLeadingTrailingSpace
{
publicstaticvoidmain(String[]args)
{
String str = " String Trim Example "; String strTrimmed = [Link]();
[Link]("Original String is: " + str);
[Link]("RemovedLeadingandtrailingspace");
[Link]("New String is: " + strTrimmed);
}}
Output:
Original String is:String Trim
Example Removed Leading and
trailing space New String is:
String Trim Example
Output:
String starts with Hello
Sample program to convert a String to Date:
import [Link];
[Link]
; import [Link];
public class JavaStringToDate
{
public static void main(String args[])
{
//Java String having date String
strDate="21/08/2011"; try
{
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
//convertJavaStringtoDateusingparsemethodofSimpleDateFormat
Datedate=[Link](strDate);
//PleasenotethatparsemethodthrowsParseExceptioniftheStringdatecouldnotbe parsed.
[Link]("Date is:"+date);
}
catch(ParseException e){
[Link]("Java String could not be converted toDate:"+e);
}
}
}
Output:
FriJan2100:00:00IST 2011
StringBuffer Class
StringBuffer is a peer class of String. While String creates strings of fixed_length,
StringBuffer creates strings of flexible length that can be modified in terms of both
length and content. Some of the most commonly used StringBuffer methods are:
1. [Link](n,‗x‘)
2. [Link](s2)
3. [Link](n,s2)
4. [Link](n)
Method Task
[Link](n,
Modifies the nth character to x
‗x‘)
[Link](s2) Appends the string s2 to s1 at the end
Inserts the string s2 at the position n of the
[Link](n,s2)
string
s1
Sets the length s1 to n. If(n<[Link]()s1is
[Link](n)
truncated. Ifn>[Link]()zeros are added to
s1.
classA
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now(16*2)+2=34i.e(oldcapacity*2)+2
}
}
classA
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now(16*2)+2=34i.e(oldcapacity*2)+2
[Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now70
}
}
VECTORS
Vector class is contained in the [Link] package. This class can be used to create a
generic array known as vector that can hold objects of any type and any number. Arrays
can be easily implemented as vectors. Vectors are created like arrays as follows:
Vectorint Vect=new Vector();
Vector list=new Vector (3);
Example:
import [Link].*;
class vector
{
public static void main(String args[])
{
Vector list=new Vector();
int length=[Link];
for(inti=0;i<length;i++)
{
[Link](args[i]);
}
[Link](―COBOL‖,2);
int size = [Link]( );
String listArray[]=new String[size];
[Link](listArray);
[Link](―List of Languages‖);
for(int I =0 ;i< size;i++)
{
[Link](listArray[i]);
}
}
}
Output:
Command line input and output are:
C:\JAVA\prog>javaLanguageVectorAdaBASICC+
+FORTRANJava List of Languages
Ada
BASIC
COBOL
C++
FORTRAN
Java
Wrapper Classes
Primitive data types like int,float,long,char and double may be converted into object types
by using the wrapper classes contained in the [Link] package.
Wrapper classes for converting Simple Types are:
Sample Program:
public class Workingdays
{
enum Days
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
public static void main(String args([])
for (Days d : [Link]( ))
{
weekend(d);
}
}
private static void weekend(Daysd)
{
if([Link]([Link])
[Link](―value=+d+'is a Holiday‖);
else
[Link]("value'+(14,is a workingday.);
}
}
Output:
value=Sunday is a Holiday
value = Monday is a Working
Day value = Tuesday is a
Working Day
value=Wednesday is a
WorkingDay value =
Thursday is a Working Day
value = Friday is a Working
Day value = Saturday is a
Working Day
Annotations
The annotations feature, introduced by J2SE 5.0,is also known as metadata. This feature is
used to merge additional Java elements with the programming elements, such as classes,
methods, parameters, local variables, packages and fields.
Metadata is stored in java class files by the compiler and these class files are used by the
JVM or by the program to find the metadata for interacting with the programming
elements. Java contains the following standard annotations:
1. @Deprecated
2. @Overrides
The following are the meta-annotations:
1. @Documented
2. @Inherited
3. @Retention
4. @Target
The following are the code that contains the declaration of an
annotation: Package [Link]:
Import [Link].*;
@Retention([Link])
@Target(([Link]))
Public @interface UnitTest
{
Stringvalue();
}
INTERFACES:MULTIPLEINHERITANCES
Introduction
Java provides an alternate approach known as interfaces to support the concept of multiple
inheritances.
Defining Interfaces
An interface is basically a kind of class. Like classes, interfaces contain methods and
variables but with a major difference. The difference is that interfaces define only
abstract methods and final fields. They syntax for defining an interface is very similar to
that for defining a class. The general form of an interface definition is:
interface InterfaceName
{
Variables declaration; methods
declaration;
}
Here, interface is the keyword and Interface Name is any valid Java variable. Variables
are declared as follows:
static final typeVariableName=Value;
Note that all variables are declared as constants. Methods declaration will contain only a
list of methods without any body statements.
return-type methodName1(parameter_list);
Anexampleforinterfacedefinitionthatcontainstwovariablesandonemethod:
interface Item
{
static final int code =1001; static
final String name=‖fan‖; void
display( );
}
The code for the method is not included in the interface and the method declaration ends
with semicolon. The class that implements this interface must define the code for the
method. example is,
interface Area
{
final static floar pi=3.142f; float
compute(floatx,floaty); void
show( );
}
Extending Interfaces
Like classes, interfaces can also be extended. That is, an interface can be sub interfaced
from other interfaces. The new sub interface will inherit all the members of the super
interface in the manner similar to subclasses. This is achieved using the keyword extends
as shown below:
interfacename2extendsname1
{
bod y of name2
}
This will enable us to use the constants in classes where the methods are not required.
Example:
interface ItemConstants
{
int code=1001; string
name="Fan";
}
interface Item extends ItemConstants
{
void display();
}
The interface item would inherit both the constants code and name into it. Note that the
variables name and code are declared like simple variables. It is allowed because all the
variables in an interface are treated as constants although the keywords final and static
are not present. We can also combine several interfaces together into a single interface.
Following declarations are valid:
interface ItemConstants
{
int code=1001;
String
name="Fan";
}
interface ItemMethods
{
void display();
}
interface Item extends ItemConstants, ItemMethods
{
..................
..................
}
Implementing Interfaces
Interfaces are used as"superclasses"whose properties are inherited by [Link] is therefore
necessary to create a class that inherits the given interface. This is done as follows:
class classname implements interfacename
{
bodyof classname
}
[Link]();
}
}
interface shape
{
public String
baseclass="shape"; public void
Draw();
}
class circle implements shape
{
public void Draw()
{
[Link]("Drawing Circle here");
}
}
Output:
Drawing Circle here
Java
Java
Font
The package name can give in import statement with class name such as:
import [Link];
Or
importpackagename.*;
Example:[Link]
Or
[Link].*;
Naming Conventions
Packages can be named using the standard Java naming rules. By convention, packages
begin with lowercase letters. This makes it easy for users to distinguish package names
from classnames when looking at an explicit reference to a class. All classnames, again by
convention, begin with an uppercase letter.
Example:
• double y = [Link](x);
•
package class method
This statement uses a fully qualified classname Math to invoke the method sqrt().
Methods begin with lowercase.
Creating Packages
First declare the name of the package using the package keyword followed by a package
name. Then define a class such as:
package firstPackage; //package declaration
publicclass FirstClass //class definition
{
…………..
…………..
}
The following are the steps to create our own packages are:
1. Declare the package at the beginning of a file using the form
package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a sub directory under the directory where the main source files are stored.
4. Store the listing as the classname . java file in the sub directory created.
5. Compile the file .This creates .class file in the sub directory.
Accessing a Package Java system package can be accessed either using a fully qualified
class name or using a shortcut approach through the import statement. The same
approaches can be used to access the user-defined packages as well. The general form of
import statement for searching a class is as follows:
import package1[.package2][package3].classname;
The following is an example of importing a particular class:
import [Link];
This can also
written as:
import packagename.*;
Here, package name may denote a single package or a hierarchy of packages. The star(*)
indicates that the compiler should search this entire package hierarchy when it
encounters a class name.
Using a Package
Example:
package package1;
public class ClassA
{
public void displayA()
{
[Link](―ClassA‖);
}}
This source file should be named Class [Link] and stored in the subdirectory package1.
Adding a Class to a Package
The simple way to add a class to an existing package is
package p1; public ClassA
{
//bodyofA
}
To add another class B to this package, the following steps to be followed:
1. Define the class and make it public.
2. Place the package
statement package p1;
Before theclass definition as follows:
package p1;
public classB
{
//bodyofB
}
3. Store this as [Link] file under the directory p1.
4. Compile [Link] [Link] will create a [Link] file and place it in the directory p1.
Hiding Classes
Some of the classes can be hide from accessing from out side of the package. Such classes
should be declared ―not public‖. For EXAMPLE:
packagep1;
public classX //public class,available outside
{
//body of X
}
Class Y //notpublic,hidden
{
//bodyofY
}
Static Import
Static import is another language feature introduced with the J2SE 5.0 release. This
feature eliminates the need of qualifying a static member with the class name. The static
import declaration is similar to that of import. The Syntax is:
import static [Link]-name;(or)
import static [Link]-name.*;
The interface can be imported using the static import statementas follows:
import static employee.employee_details.Salary_increment;
Here, employee is package name, employee_details is subpackage and Salary_increment
is static member name.
Example:
MULTITHREADED PROGRAMMING
Introduction
The ability to execute several programs simultaneously is called multitasking. In system‘s
terminology, it is called multithreading. Multithreading is a conceptual programming
paradigm where a program (process) is divided into two or more subprograms
(processes), which can be implemented at the same time in parallel. A thread is similar
to a program that has a single flow of control. Java enables us to use multiple flows of
control in developing programs.
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 heart and soul of any thread. It
makes up the entire body of a thread and is the only method in which the threads
behavior can be implemented. A typical run() would appear as follows:
public void run()
{
..................
..................
}
A new thread can be created in 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 theThread Class
We can make our class runnable as thread by extending the class [Link]. This
gives us access to all the thread methods directly. It includes the following steps:
1. Declare the class as extending theThread class.
2. Implement the run() method that is responsible for executing sequence of code that
the thread will execute.
3. Createathreadobjectandcallthestart()methodtoinitiatethethreadexecution.
a) Declaring the Class
The Thread class can be extended as follows:
class MyThread extends Thread
{
...................
...................
}
Start Stop
Runnable Dead
2. Runnable state
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are
waiting for execution.
The thread that relinquishes control joins the queue at the end and again waits for its turn.
This process of assigning time to thread is known as time-slicing.
yield
Running
thread
Runnable threads
3. Running state
Running means that the processor has given its time to the thread for its execution.
a) It has been suspended using suspend() method. A suspended thread can be revived
by using the resume() method.
b) It has been made to sleep. We can put a thread to sleep for a specified time period
using the method sleep where time is in milliseconds.
c) It has been told to wait until some event occurs. This is done using the wait()
method. The thread can be scheduled to run again using the notify() method.
Suspend,sleep(),wait
Running Suspended
Resume,alert,notify
4. Blocked state
A thread is said to be blocked when it is prevented from entering into the runnable state
and subsequently the running state. This happens when the thread is suspended, sleeping
or waiting in order to satisfy certain requirements.
5. Dead state
Every thread has a life cycle. A running thread ends its life when it has completed
executing its run() method. It is a natural death.
Using Thread Methods
We have discussed how Thread class methods can be used to control the behavior of a
thread. We have used the methods start() and run(). Then the use of yield(), sleep() and
stop() methods.
Example:
class A extends Thread
{
public void run()
{
................
...............
}}
class B extends Thread
{
public void run()
{
................
...............
}}
class C extends Thread
{
public void run()
{
................
...............}}
class ThreadTest
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
.....................
.....................
}}
Example for Yield() thread:
public class RunnablePotato implements Runnable
{
public void run()
{
while(true)
{
[Link]([Link]().getName());
[Link]();// let another thread run for a while
}
}
}
Normally , we would have to use [Link]().yield() to get your hands on the
current thread, and then call yield().Because this pattern is so common, however, the
Thread class can be used as a shortcut.
The yield()method explicitly gives any other threads that want to run a chance to begin
running. (If there are no threads waiting to run, the thread that made the yield() simply
continues.) In our example, there's another thread that's just dying to run, so when you
now execute the class Thread Tester, it should output the following:
onepotato
twopotato
onepotato
twopotato
onepotato
twopotato
...
This output will be the same regardless of the type of scheduler you have.
Thread Exceptions
The call to sleep() method is enclosed in a try block and followed by a catch block. This is
necessary because the sleep() method throws an exception, which should be caught. Java
run system will throw Illegal Thread State Exception whenever we attempt to invoke a
method that a thread cannot handle in the given state. The same is true with the
suspend() method when its used on a blocked thread. The catch statement may take one
of the following forms:
catch(ThreadDeath e)
{
.................
................
}
catch(InterruptedException e)
{
................
................
}
catch(IllegalArgumentException e)
{
..................
..................
}
catch(Exception e)
{
....................
....................
}
Thread Priority
In Java each thread is assigned a priority, which affects the order in which it is scheduled
for running. The threads that we have discussed so far are of the same priority.
Java permits us to set the priority of a thread using the setPriority() method as follows:
[Link](intNumber);
For athread of lower priority to gain control,one of the following things should happen:
1. It stops running at the end of run().
2. It is made to sleep using sleep().
3. It is told to wait using wait().
Example:
class A extends Thread
{
public void run()
{
................
...............
}}
class B extends Thread
{
public void run()
{
................
...............
}}
class C extends Thread
{
public void run()
{
................
...............
}}
class ThreadTest
{
public static void main(String args[])
{
A threadA=new A();
B threadB=newB();
C threadC=newC();
.....................
.....................
}}
Sample program:
public class Main
{
public static void main(String[] args)throws Exception
{
Thread thread1=new Thread(newTestThread(1));
Threadt hread2=new
Thread(newTestThread(2));
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]();
[Link]
();
[Link]
n();
[Link]
n();
[Link]("The priority has been set.");
}
}
Output:
The priority has been set.
Sample program:
//Create a second thread by extending
Thread class NewThread extends Thread
{
NewThread()
{
// Create a new, second thread
super("Demo Thread");
[Link]("Childthread:"+this
); start( ); // Start the thread
}
//This is the entry point for the second
thread. public void run()
{
try
{
for(inti=5;i >0; i--)
{
[Link]("ChildThread:"+i);
[Link](500);
}
}
catch(InterruptedException e)
{
[Link]("Child interrupted.");
}
[Link]("Exiting childthread.");
}
}
class ExtendThread
{
public static void main(String args[])
{
new NewThread();//create a new thread try
{
for(inti=5;i >0;i—)
{
[Link]("Main Thread:"+i);
[Link](1000);
}
}catch(InterruptedException e)
{
[Link]("Main thread interrupted.");
}
[Link]("Main thread exiting.");
}
}
Output:
Childthread:Thread[DemoThread,5,main]
Main Thread: 5
ChildThread:5
ChildThread:4
MainThread:4
ChildThread:3
ChildThread:2
MainThread:3
Child Thread: 1
Exitingchildthread.
Main Thread: 2
Main Thread: 1
Mainthreadexiting.
Output:
Enter the number to check..
121
Numberis121
121isapalindromenumber
Synchronization
So far we have seen threads that use their own data and methods provided inside their
run() methods. Depending on the situation, we may get strange results. Java enables us to
overcome this problem using a technique known as Synchronization. In case of Java, the
keyword synchronized helps to solve such problems by keeping a watch on such
locations.
Example:
synchronized void update()
{
.......................
. //code here is synchronized
}
It is also possible to mark a block of code as synchronized as shown below:
synchronized (lock-object)
{
.......................
....................... }
Whenever a thread has completed its work of using synchronized method(or block of
code),it will hand over the monitor to the next thread that is ready to use the same
resource. Deadlock is the condition on which the waiting threads rely on to gain control
does not happen. For example, assume that the thread A must access Method1 before it
can release Method2,but the thread B cannot release Method1 until it gets hold of
[Link] these are mutually exclusive conditions, a deadlock occurs. The code
below illustrates this:
ThreadA
synchronizedmethod2()
{
synchronizedmethod1()
{
.......................
.......................
}}
ThreadB
synchronizedmethod1()
{
synchronizedmethod2()
{
.......................
.......................}}
Implementing the 'Runnable' Interface
The Runnable interface declares the run()method that is required for implementing threads
in our programs. To do this, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run()method.
3. Create a thread by defining an object that is instantiated from this"runnable"class as
the target of the thread.
4. Call the thread's start() method to run the thread.
If the direct reference to the thread threadX is not required, then we may use a shortcut as
shown below:
new Thread (new X()).start();
class X implements
Runnable{ public void run() {
................
. }}
class RunnableTest{
public static void main(String args[])
{
X runnable=new X();
Thread threadX=new Thread(runnable);
[Link]();
. }}
Sample program using threads:
class thrun implements
Runnable{ Thread t;
boolean runn = true;
thrun(Stringst,intp){
t=newThread(this,st);
[Link](p);
[Link]();}
public void run(){
[Link]("Thread name : " + [Link]());
[Link]("ThreadPriority:"+[Link]());}}
class priority{
public static void main(String args[]){
[Link]().setPriority(Thread.MAX_PRIORITY);
thrunt1=newthrun("Thread1",Thread.NORM_PRIORITY+2);
thrun t2 = new thrun("Thread2",Thread.NORM_PRIORITY - 2);
[Link]("Main Thread : " + [Link]());
[Link]("Main Thread Priority:"+[Link]().getPriority());}}
Output:
Thread name: Thread1
Main Thread:Thread[main,10,main]
Thread name : Thread2
Thread Priority:7
Main Thread
Priority:10 Thread
Priority :