SlideShare une entreprise Scribd logo
1  sur  105
Remaining JAVA manual
Remaining manual of JAVA 2
F. Ansari
8/10/2014
2
Contents
Program 75:...................................................................................................................................................6
Solution:........................................................................................................................................................6
Output: ..........................................................................................................................................................8
Discussion:....................................................................................................................................................8
Program 76:...................................................................................................................................................9
Solution:........................................................................................................................................................9
Output: ........................................................................................................................................................13
Discussion:..................................................................................................................................................13
Program 77:.................................................................................................................................................14
Solution:......................................................................................................................................................14
Output: ........................................................................................................................................................18
Discussion:..................................................................................................................................................18
Program 78:.................................................................................................................................................18
Solution:......................................................................................................................................................18
Output: ........................................................................................................................................................22
Discussion:..................................................................................................................................................22
Program 79:.................................................................................................................................................23
Solution:......................................................................................................................................................23
Output: ........................................................................................................................................................27
Discussion:..................................................................................................................................................27
Program 80:.................................................................................................................................................27
Solution:......................................................................................................................................................27
Output: ........................................................................................................................................................30
Discussion:..................................................................................................................................................31
Program 81:.................................................................................................................................................31
Solution:......................................................................................................................................................31
Output: ........................................................................................................................................................34
Discussion:..................................................................................................................................................34
Program 82:.................................................................................................................................................35
Solution:......................................................................................................................................................35
Output: ........................................................................................................................................................38
3
Discussion:..................................................................................................................................................38
Program 83:.................................................................................................................................................38
Solution:......................................................................................................................................................38
Output: ........................................................................................................................................................42
Discussion:..................................................................................................................................................43
Program 84:.................................................................................................................................................43
Solution:......................................................................................................................................................43
Output: ........................................................................................................................................................47
Discussion:..................................................................................................................................................47
Program 85:.................................................................................................................................................47
Solution:......................................................................................................................................................47
Output: ........................................................................................................................................................52
Discussion:..................................................................................................................................................52
Program 86:.................................................................................................................................................53
Solution:......................................................................................................................................................53
Output: ........................................................................................................................................................55
Discussion:..................................................................................................................................................55
Program 87:.................................................................................................................................................55
Solution:......................................................................................................................................................55
Output: ........................................................................................................................................................57
Discussion:..................................................................................................................................................57
Program 88:.................................................................................................................................................57
Solution:......................................................................................................................................................57
Output: ........................................................................................................................................................60
Discussion:..................................................................................................................................................60
Program 89:.................................................................................................................................................60
Solution:......................................................................................................................................................60
Output: ........................................................................................................................................................61
Discussion:..................................................................................................................................................62
Program 90:.................................................................................................................................................62
Solution:......................................................................................................................................................62
Output: ........................................................................................................................................................64
4
Discussion:..................................................................................................................................................64
Program 91:.................................................................................................................................................65
Solution:......................................................................................................................................................65
Output: ........................................................................................................................................................68
Discussion:..................................................................................................................................................68
Program 92:.................................................................................................................................................68
Solution:......................................................................................................................................................68
Output: ........................................................................................................................................................71
Discussion:..................................................................................................................................................71
Program 93:.................................................................................................................................................71
Solution:......................................................................................................................................................71
Output: ........................................................................................................................................................75
Discussion:..................................................................................................................................................75
Program94:..................................................................................................................................................75
Solution:......................................................................................................................................................75
Output: ........................................................................................................................................................78
Discussion:..................................................................................................................................................78
Program 95:.................................................................................................................................................78
Solution:......................................................................................................................................................78
Output: ........................................................................................................................................................81
Discussion:..................................................................................................................................................81
Program 96:.................................................................................................................................................81
Solution:......................................................................................................................................................81
Output: ........................................................................................................................................................84
Discussion:..................................................................................................................................................84
Program 97:.................................................................................................................................................85
Solution:......................................................................................................................................................85
Output: ........................................................................................................................................................87
Discussion:..................................................................................................................................................87
Program 98:.................................................................................................................................................88
Solution:......................................................................................................................................................88
Output: ........................................................................................................................................................90
5
Discussion:..................................................................................................................................................90
Program 99:.................................................................................................................................................90
Solution:......................................................................................................................................................90
Output: ........................................................................................................................................................92
Discussion:..................................................................................................................................................92
Program 100:...............................................................................................................................................93
Solution:......................................................................................................................................................93
Output: ........................................................................................................................................................96
Discussion:..................................................................................................................................................97
Program 101:...............................................................................................................................................97
Solution:......................................................................................................................................................97
Output: ........................................................................................................................................................98
Discussion:..................................................................................................................................................99
Program 102:...............................................................................................................................................99
Solution:......................................................................................................................................................99
HTML Code:.......................................................................................................................................100
Output: ......................................................................................................................................................101
Discussion:................................................................................................................................................101
Program 103:.............................................................................................................................................102
Solution:....................................................................................................................................................102
HTML Code:.....................................................................................................................................102
Output: ......................................................................................................................................................103
Discussion:................................................................................................................................................103
Program 104:.............................................................................................................................................103
Solution:....................................................................................................................................................103
HTML Code:.....................................................................................................................................104
Output: ......................................................................................................................................................105
Discussion:................................................................................................................................................105
6
Program 75:
Write a code using the concept of multithreading that controls the main
thread.
Solution:
// controlling the main Thread.
class CurrentThreadDemo {
/* this line contains a keyword class that shows that a class is going to start and
CurrentThreadDemo is the name of this class. Opening curly brace { shows that form here a
class’ definition is going to begin */
// Your program begin with a call to main.
public static void main(String args[]){
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
Thread t = Thread.currentThread();
// a thread defines a separate path of execution & here an object/local variable of thread is
declared and initialized
System.out.println("Current thread: " + t);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will print the current thread
that is stored in the object of thread t */
// change the name of the thread
t.setName("My Thread");
/* In this line of code the name of the Thread is changed by calling a built in function setName()
that set the name by taking a String as an argument inside the paranthesis.*/
System.out.println("After name change: " + t);
7
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will print the thread after its
name changed that is stored in the object t of thread */
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
for(int n = 5; n > 0; n--) {
/*a for loop is declared here it contains three parts initialization that initializes n to 5, condition
i.e n is greater than 0, iteration i.e decrement of n. Firstly loop initialize n to 5 and then it will
check the condition that either it is true or not, if it is true then the next statement will be
compiled, after that control/system will pass to the iteration process then it will check the
condition if it is fulfilled then the statement given below will be executed again i.e it will go on
decreasing the value of n by 1 until the condition is not satisfied*/
System.out.println(n);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. It will display the value of n*/
Thread.sleep(1000);
// thread will sleep/paused for the time given in parenthesis
} // closing curly brace } is used to close the definition of for loop
} catch (InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println("Main thread interrupted");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. If any exception occurs then this line of code
will display that Main thread interrupted */
} // closing curly brace } is used to close the definition of catch block
} // closing curly brace } is used to close the definition of main() method
8
} // closing curly brace } is used to close the definition of class
Output:
Discussion:
The program contains a reference to the current thread, obtained by calling
currentThread( ), and this reference is stored in the local variable t. Then the program displays
information about the thread. The program then calls setName( ) method to change the name of
the thread. Information about the thread is then displayed again. Then a loop starts from five and
it sleeps or pauses for one second between each line. Then the try/catch block starts after this
loop. If the sleep( ) method in Thread will throw an InterruptedException then it will be
caught and displayed by the catch block.
9
Program 76:
Using the concept of multithreading write a code that implements
runnable & will not run until the start() method written within thread is
called.
Solution:
// Create a second thread.
class NewThread implements Runnable {
/* this line contains a keyword class that shows that a class is going to start and NewThread is
the name of this class. Opening curly brace { shows that form here a class’ definition is going
to begin. It implements Runnable an abstract class */
Thread t;
// t is the local variable or an object of Thread is initialized here and stores.
NewThread() {
// Constructor of NewThread() class. Inside NewThread’s constructor, a new Thread object is
created
t = new Thread(this, "Demo Thread");
// Create a new, second thread
System.out.println("Child thread: " + t);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
/* public is a keyword which means that this method is publically accessible, void means that it
has no return type, run() is the abstract method of abstract class Runnable and it is implemented
here, Opening Curly Brace { means that the method’s def. is going to start. */
10
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
for(int i = 5; i > 0; i--) {
/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition
i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will
check the condition that either it is true or not, if it is true then the next statement will be
compiled, after that control/system will pass to the iteration process then it will check the
condition if it is fulfilled then the statement given below will be executed again i.e it will go on
increasing the value of i by 1 until the condition is not satisfied*/
System.out.println("Child Thread: " + i);
// This line of code will display the String written inside the parenthesis for ith
time.
Thread.sleep(500);
// thread will sleep/paused for the time given in parenthesis
}
// closing curly brace } is used to close the definition of for loop.
} catch (InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println("Child interrupted.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis if any exception occurs. */
}
System.out.println("Exiting child thread.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
11
} // closing curly brace } is used to close the definition of run() method
} // closing curly brace } is used to close the definition of class
class ThreadDemo {
/* this line contains a keyword class that shows that a class is going to start and ThreadDemo is
the name of this class. Opening curly brace { shows that form here a class’ definition is going
to begin */
// Your program begin with a call to main.
public static void main(String args[]) {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
new NewThread(); // create a new thread
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
for(int i = 5; i > 0; i--) {
/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition
i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will
check the condition that either it is true or not, if it is true then the next statement will be
compiled, after that control/system will pass to the iteration process then it will check the
condition if it is fulfilled then the statement given below will be executed again i.e it will go on
increasing the value of i by 1 until the condition is not satisfied*/
System.out.println("Main Thread: " + i);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis.*/
Thread.sleep(1000);
12
// thread will sleep/paused for the time given in parenthesis
}
} catch (InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println("Main thread interrupted.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis if any exception occurs. */
}
System.out.println("Main thread exiting.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
13
Output:
Discussion:
In this program the first thread is used to call the run() method using this object. Then
start( ) is called, which starts the thread at the run( ) method. This causes the thread’s for loop
to begin. After calling start( ), NewThread’s constructor returns to main( ). When the main
thread starts, it enters its for loop. Both threads continue running, until their loops finish. Hence
they display the output.
14
Program 77:
Write a code using multithreading concept by extending Thread class.
Solution:
// Create a second thread by extending Thread
class NewThread extends Thread {
/* this line contains a keyword class that shows that a class is going to start and NewThread is
the name of this class and this class extends Thread. Opening curly brace { shows that form
here a class’ definition is going to begin */
NewThread() {
// Constructor of NewThread() class. Inside NewThread’s constructor, a new Thread object is
created
super("Demo Thread");
/* the call to super( ) inside NewThread invokes the following form of the Thread
constructor i.e public Thread(String threadName). Here, threadName specifies the name of the
thread.*/
System.out.println("Child thread: " + this);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will print the current thread
that is stored in the this keyword. */
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
/* public is a keyword which means that this method is publically accessible, void means that it
has no return type, run() is the abstract method of abstract class Runnable and it is implemented
here, Opening Curly Brace { means that the method’s def. is going to start. */
try {
15
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
for(int i = 5; i > 0; i--) {
/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition
i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will
check the condition that either it is true or not, if it is true then the next statement will be
compiled, after that control/system will pass to the iteration process then it will check the
condition if it is fulfilled then the statement given below will be executed again i.e it will go on
increasing the value of i by 1 until the condition is not satisfied*/
System.out.println("Child Thread: " + i);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will print what is written
inside it. */
Thread.sleep(500);
// thread will sleep/paused for the time given in parenthesis
}
} catch (InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println("Child interrupted.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will print what is written
inside it if any exception occurs and caught by catch block.*/
}
System.out.println("Exiting child thread.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will print the statement
written inside it. */
16
}
}
class ExtendThread {
/* this line contains a keyword class that shows that a class is going to start and ExtendThread
is the name of this class. Opening curly brace { shows that form here a class’ definition is going
to begin */
public static void main(String args[]) {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
new NewThread(); // create a new thread
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
for(int i = 5; i > 0; i--) {
/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition
i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will
check the condition that either it is true or not, if it is true then the next statement will be
compiled, after that control/system will pass to the iteration process then it will check the
condition if it is fulfilled then the statement given below will be executed again i.e it will go on
increasing the value of i by 1 until the condition is not satisfied*/
System.out.println("Main Thread: " + i);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
Thread.sleep(1000);
}
17
} catch (InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println("Main thread interrupted.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis if any exception occurs and caught by catch block. */
}
System.out.println("Main thread exiting.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
18
Output:
Discussion:
This program generates the same output as the above program generates. The thread is
created by instantiating an object of NewThread, which is derived from Thread. Notice the call
to super( ) inside NewThread. This runs the Thread constructor and super performs the erasing
behavior.
Program 78:
Write a code using multithreading concept that creates multiple threads
Solution:
// Create multiple threads.
class NewThread implements Runnable {
19
/* this line contains a keyword class that shows that a class is going to start and NewThread is
the name of this class and it implements an abstract class Runnable(). Opening curly brace {
shows that form here a class’ definition is going to begin */
String name; // name of thread
Thread t;
// t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s
constructor, a new Thread object is created
NewThread(String threadname) {
// An argument Constructor of NewThread() class. Inside NewThread’s constructor, a new
Thread object is created
name = threadname;
// String is initialized here.
t = new Thread(this, name);
// Create a new, second thread. t is initialized here and reference to the name is stored in it.
System.out.println("New thread: " + t);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will print the new thread that
is stored in the object t of thread */
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
/* public is a keyword which means that this method is publically accessible, void means that it
has no return type, run() is the abstract method of abstract class Runnable and it is implemented
here, Opening Curly Brace { means that the method’s def. is going to start. */
try {
20
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
for(int i = 5; i > 0; i--) {
/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition
i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will
check the condition that either it is true or not, if it is true then the next statement will be
compiled, after that control/system will pass to the iteration process then it will check the
condition if it is fulfilled then the statement given below will be executed again i.e it will go on
increasing the value of i by 1 until the condition is not satisfied*/
System.out.println(name + ": " + i);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
Thread.sleep(1000);
// thread will sleep/paused for the time given in parenthesis
}
} catch (InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println(name + "Interrupted");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
}
System.out.println(name + " exiting.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis.*/
21
}
}
class MultiThreadDemo {
// Your program begin with a call to main.
public static void main(String args[]) {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
// new threads started here
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
// wait for other threads to end
Thread.sleep(10000);
// thread will sleep/paused for the time given in parenthesis
} catch (InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println("Main thread Interrupted");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. If any exception occurs then this line of code
will display that Main thread interrupted */
22
}
System.out.println("Main thread exiting.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
Output:
Discussion:
This program once started, all three new/ child threads start executing/ running. Notice
the call to sleep(10000) in main( ). This causes the main thread to sleep for ten seconds and
ensures that it will finish last.
23
Program 79:
Write a code that demonstrate thread priorities
Solution:
// Demonstrate thread priorities.
class clicker implements Runnable {
/* this line contains a keyword class that shows that a class is going to start and clicker is the
name of this class and it implements Runnable an abstract class. Opening curly brace { shows
that form here a class’ definition is going to begin */
long click = 0; // local variable to type ling initialized to 0
Thread t;
// t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s
constructor, a new Thread object is created
private volatile boolean running = true;
/* here a private volatile Boolean variable is declared and initialized. Private means can’t b
accessible outside the class and volatile variable means the variable whose value is always held in
main memory so that it can be accessed by different threads. */
public clicker(int p) {
// An argument Constructor of Clicker() class.
t = new Thread(this);
// t is initialized here
t.setPriority(p);
// priority is been set here calling setPriority() function
}
public void run() {
/* public is a keyword which means that this method is publically accessible, void means that it
has no return type, run() is the abstract method of abstract class Runnable and it is implemented
here, Opening Curly Brace { means that the method’s def. is going to start. */
while (running) {
24
click++;
}
// if running then click will keep on incrementing
}
public void stop() {
///* public is a keyword which means that this method is publically accessible, void means that
it has no return type, stop() is the method to stop the running thread. Opening Curly Brace {
means that the method’s def. is going to start. */
running = false;
// to stop we will make running false
}
public void start() {
t.start();
}
// this method will start the thread
}
class HiLoPri {
/* this line contains a keyword class that shows that a class is going to start and HiLoPri is the
name of this class. Opening curly brace { shows that form here a class’ definition is going to
begin */
// Your program begin with a call to main.
public static void main(String args[]) {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
25
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
// here 2 objects of class clicker are created and instantiated i.e hi, lo and both are set to default
priority using NORM_PRIORITY but by +2 & -2 hi will b of high n lo will b of low priority
lo.start();
hi.start();
// here both objects’s working starts using start() methd
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
Thread.sleep(10000);
// thread will sleep/paused for the time given in parenthesis
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis if any exception occurs. */
}
lo.stop();
hi.stop();
// here the working of both the instances of class will stop by calling stop() method
// Wait for child threads to terminate.
try {
26
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
hi.t.join();
lo.t.join();
// here join() method is called that waits for a thread to finish
} catch (InterruptedException e) {
System.out.println("InterruptedException
caught");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis if any exception occurs.*/
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. These lines of code will display the Strings
written inside the parenthesis. */
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
27
Output:
Discussion:
Thread priorities are used by the thread scheduler to decide when each thread is allowed
to run. Higher priority threads get more time then lower priority threads. To set the thread
priority setPriority() method is used which is a member of Thread. In this program an instance of
thread is initialized and setPriority() method is called through it. Then run(), stop() and start()
method is called. Then main method is declared in which the class instantiated. Then a join()
method is called with the class’ instances that method waits for a thread to finish. Then high
level and low level threads are stored in hi and lo objects respectively and then displayed as
above.
Program 80:
Write a code that will not synchronized
Solution:
// This program is not synchronized.
class Callme {
/* this line contains a keyword class that shows that a class is going to start and Callme is the
name of this class. Opening curly brace { shows that form here a class’ definition is going to
begin */
void call(String msg) {
System.out.print("[" + msg);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
28
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. If any exception occurs then this line of code
will display Interrupted */
}
System.out.println("]");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
}
}
class Caller implements Runnable {
String msg;
Callme target; // instance of class
Thread t;
// t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s
constructor, a new Thread object is created
public Caller(Callme targ, String s) {
target = targ;
29
msg = s;
t = new Thread(this); // t is initializes
t.start(); // thread starts
}
public void run() {
/* public is a keyword which means that this method is publically accessible, void means that it
has no return type, run() is the abstract method of abstract class Runnable and it is implemented
here, Opening Curly Brace { means that the method’s def. is going to start. */
target.call(msg); // method is called
}
}
class Synch {
/* this line contains a keyword class that shows that a class is going to start and Synch is the
name of this class. Opening curly brace { shows that form here a class’ definition is going to
begin */
// Your program begin with a call to main.
public static void main(String args[]) {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// class’ objects are initialized n declared
30
// wait for threads to end
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
ob1.t.join();
ob2.t.join();
ob3.t.join();
// here join() method is called that waits for a thread to finish
} catch(InterruptedException e) {
System.out.println("Interrupted");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
}// closing curly brace } is used to close the definition of catch()
block
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
Output:
31
Discussion:
This program shows that how the output will look like without synchronization. A
class Callme is created first. Then strings are declared and displayed. In class Caller that
implements Runnable a new thread is starts then call() method is called in run method that calls
the String throught msg. Then try catch block try to synchronize the string as shown in output
also using join() method.
Program 81:
write a code that uses synchronized block
Solution:
// This program uses a synchronized block.
class Callme {
/* this line contains a keyword class that shows that a class is going to start and Callme is the
name of this class. Opening curly brace { shows that form here a class’ definition is going to
begin */
void call(String msg) {
System.out.print("[" + msg);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
Thread.sleep(1000);
// thread will sleep/paused for the time given in parenthesis
} catch (InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println("Interrupted");
32
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. If any exception occurs then this line of code
will display Interrupted */
}
System.out.println("]");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis.*/
}
}
class Caller implements Runnable {
String msg; // a string msg is declared
Callme target; // class’s object
Thread t;
// t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s
constructor, a new Thread object is created
public Caller(Callme targ, String s) {
// 2 argument constructor
target = targ;
msg = s;
t = new Thread(this); // t is initializes
t.start(); // t starts
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
33
target.call(msg); // call() is called
}
}
}
class Synch1 {
/* this line contains a keyword class that shows that a class is going to start and Synch1 is the
name of this class. Opening curly brace { shows that form here a class’ definition is going to
begin */
public static void main(String args[]) {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// class’ instances are declared and initializes
// wait for threads to end
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
ob1.t.join();
ob2.t.join();
ob3.t.join();
34
// here join() method is called that waits for a thread to finish
} catch(InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println("Interrupted");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis if any exception occurs.*/
} // end of catch block
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
Output:
Discussion:
This program shows that how the output will look like if it is synchronized. A class
Callme is created first. Then another class Synch1 is created that contains the main method. Then
a call method is declared having msg string as a parameter and then displays it too. Then try
catch block is declared that displays the strings. In class Caller that implements Runnable a new
thread is starts then caller() method is declared having 2 arguments and it starts the thread using
its object. Then synchronize calls to Call() method is which synchronized block is declared then
in the main method creating 3 objects of Callme class are declared and initialized . Synchronized
statement is used inside the caller’s run() method and shows the synchronized output.
35
Program 82:
write an incorrect implementation of a producer and consumer
Solution:
// An incorrect implementation of a producer and consumer.
class Q {
/* this line contains a keyword class that shows that a class is going to start and Q is the name of
this class. Opening curly brace { shows that form here a class’ definition is going to begin */
int n; // local variable of type int
synchronized int get() {
// When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time so for this synchronized get() method is
used
System.out.println("Got: " + n);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
return n; // it will return n
}
synchronized void put(int n) {
// When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time so for this synchronized put() method is
used
this.n = n; // reference of object n is stored
System.out.println("Put: " + n);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
}
36
}
class Producer implements Runnable {
/* this line contains a keyword class that shows that a class is going to start and Producer is the
name of this class and it implements Runnable an abstract class. Opening curly brace { shows
that form here a class’ definition is going to begin */
Q q; // instance of class Q
Producer(Q q) {
// Constructor of Producer class.
this.q = q; // stores reference of q
new Thread(this, "Producer").start(); // new Thread starts
}
public void run() {
/* public is a keyword which means that this method is publically accessible, void means that it
has no return type, run() is the abstract method of abstract class Runnable and it is implemented
here, Opening Curly Brace { means that the method’s def. is going to start. */
int i = 0; /// a variable i of type int
while(true) {
q.put(i++); // if condition is true then i will increment
}
}
}
class Consumer implements Runnable {
/* this line contains a keyword class that shows that a class is going to start and Consumer is the
name of this class & it implements Runnable an abstract class. Opening curly brace { shows
that form here a class’ definition is going to begin */
Q q; // instance of class Q
Consumer(Q q) {
37
// Constructor of Consumer class.
this.q = q; // reference of q is stored
new Thread(this, "Consumer").start(); // new thread starts here
}
public void run() {
/* public is a keyword which means that this method is publically accessible, void means that it
has no return type, run() is the abstract method of abstract class Runnable and it is implemented
here, Opening Curly Brace { means that the method’s def. is going to start. */
while(true) {
q.get(); // if true then get() function works
}
}
}
class PC {
/* this line contains a keyword class that shows that a class is going to start and PC is the name
of this class. Opening curly brace { shows that form here a class’ definition is going to begin */
// Your program begin with a call to main.
public static void main(String args[]) {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
38
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
Output:
Discussion:
In this program put(), get() and run methods are used. Consumer the threaded object that
is consuming queues entries is also used. In Q put and get methods are synchronized, nothing
stops the producer from overrunning the consumer, nor will anything stop the consumer from
consuming the same queue value twice. Thus, we get the erroneous output shown above.
Program 83:
write a correct implementation of a producer and consumer.
Solution:
// A correct implementation of a producer and consumer.
class Q {
/* this line contains a keyword class that shows that a class is going to start and Q is the name of
this class. Opening curly brace { shows that form here a class’ definition is going to begin */
int n; // local variable is initialized
boolean valueSet = false;
39
// a variable of type Boolean is initialized and declared
synchronized int get() {
// When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time so for this synchronized get() method is
used
while(!valueSet)
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
wait();
// wait() tells the calling object to gine up the monitor and go to sleep until some other threads
enter the same monitor and calls the notify.
} catch(InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println("InterruptedException caught");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis if any exception occurs. */
}
System.out.println("Got: " + n);
//This line of code will display the String written inside the parenthesis.
valueSet = false;
notify();
// notify() method wakes up the first thread that called wait() on the same object
return n; // returns n
}
synchronized void put(int n) {
40
while(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
//If any exception occurs then this line of code will display that InterruptedException caught.
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
// This line of code will display the String written inside the parenthesis.
notify();
}
}
class Producer implements Runnable {
/* this line contains a keyword class that shows that a class is going to start and Producer is the
name of this class & it implements Runnable an abstract class. Opening curly brace { shows
that form here a class’ definition is going to begin */
Q q;
Producer(Q q) {
this.q = q; // stores reference of q
new Thread(this, "Producer").start(); // new thread starts
}
public void run() {
41
/* public is a keyword which means that this method is publically accessible, void means that it
has no return type, run() is the abstract method of abstract class Runnable and it is implemented
here, Opening Curly Brace { means that the method’s def. is going to start. */
int i = 0; // local variable of type int
while(true) {
q.put(i++);
// if true the condition is then i will increases
}
}
}
class Consumer implements Runnable {
/* this line contains a keyword class that shows that a class is going to start and Consumer is the
name of this class & it implements Runnable an abstract class. Opening curly brace { shows
that form here a class’ definition is going to begin */
Q q;
Consumer(Q q) {
this.q = q; // stores reference of q
new Thread(this, "Consumer").start();
// new thread starts here
}
public void run() {
while(true) {
q.get();
}
}
}
class PCFixed {
42
/* this line contains a keyword class that shows that a class is going to start and PCFixed is the
name of this class. Opening curly brace { shows that form here a class’ definition is going to
begin */
public static void main(String args[]) {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
Output:
43
Discussion:
In this program inside get() method another method wait() is called. This causes its
execution to suspend until the Producer Tell us that some data is ready is execute. When this
happens, execution inside get() starts. After the data has been obtained, get() calls notify()
method. Using put() method more data will be added and then again the wait() method is called,
which stops the execution until the data is removed from queue. When execution resumes, the
next item of data is put in the queue, and notify() method is called. This tells the Consumer that it
should now remove it.
Program 84:
write an example of deadlock
Solution:
// An example of deadlock.
class A {
/* this line contains a keyword class that shows that a class is going to start and A is the name of
this class. Opening curly brace { shows that form here a class’ definition is going to begin */
synchronized void foo(B b) {
// When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time so for this synchronized put() method is
used
String name = Thread.currentThread().getName();
// get the name of current thread
System.out.println(name + " entered A.foo");
// This line of code will display the String written inside the parenthesis.
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
Thread.sleep(1000);
// thread sleeps/pauses for given interval of time
} catch(Exception e) {
44
System.out.println("A Interrupted");
// If any exception occurs then this line of code will display the String written inside the
parenthesis.
}
System.out.println(name + " trying to call B.last()");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
b.last(); // last method is called
}
synchronized void last() {
// When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time so for this synchronized get() method is
used
System.out.println("Inside A.last");
// This line of code will display the String written inside the parenthesis.
}
}
class B {
synchronized void bar(A a) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
// This line of code will display the String written inside the parenthesis.
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
Thread.sleep(1000);
45
} catch(Exception e) {
System.out.println("B Interrupted");
// If any exception occurs then this line of code will displays the String written inside the
parenthesis.
} // end of catch block
System.out.println(name + " trying to call A.last()");
// This line of code will display the String written inside the parenthesis.
a.last();
}
synchronized void last() {
System.out.println("Inside A.last");
// This line of code will display the String written inside the parenthesis.
}
}
class Deadlock implements Runnable {
/* this line contains a keyword class that shows that a class is going to start and Deadlock is the
name of this class & it implements Runnable an abstract class. Opening curly brace { shows
that form here a class’ definition is going to begin */
A a = new A(); // an object of class A in initialized and declared
B b = new B(); // an object of class B in initialized and declared
Deadlock() { // constructor of the class
Thread.currentThread().setName("MainThread");
// set the name of default constructor
Thread t = new Thread(this, "RacingThread");
// new thread is initialized
t.start();
46
a.foo(b); // get lock on a in this thread.
System.out.println("Back in main thread");
// This line of code will display the String written inside the parenthesis.
}
public void run() {
b.bar(a); // get lock on b in other thread.
System.out.println("Back in other thread");
// This line of code will display the String written inside the parenthesis.
}
// Your program begin with a call to main.
public static void main(String args[]) {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
new Deadlock();
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
47
Output:
Discussion:
In this program deadlock is used which is a special type of error that needs to be avoid. It
relates specifically to multitasking which occurs when two threads have a circular dependency
on a pair of synchronized objects. As the program has deadlocked, we have to press CTRL-C to
end the program. The RacingThread owns the monitor on b, while it is waiting for the monitor
on a. At the same time, MainThread owns a and is waiting to get b. This program will never
complete.
Program 85:
write a code that demonstrates the use of suspend() and resume().
Solution:
// Using suspend() and resume().
class NewThread implements Runnable {
/* this line contains a keyword class that shows that a class is going to start and NewThread is
the name of this class & it implements Runnable. Opening curly brace { shows that form here a
class’ definition is going to begin */
String name;
// name of thread. A variable of type String known as name
Thread t;
// a thread t is declared
NewThread(String threadname) { // an argument constructor is created
48
name = threadname;
t = new Thread(this, name);
// thread is initialized and stores reference of name
System.out.println("New thread: " + t);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will print the new thread that
is stored in the object of thread i.e t */
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
for(int i = 15; i > 0; i--) {
/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition
i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will
check the condition that either it is true or not, if it is true then the next statement will be
compiled, after that control/system will pass to the iteration process then it will check the
condition if it is fulfilled then the statement given below will be executed again i.e it will go on
increasing the value of i by 1 until the condition is not satisfied*/
System.out.println(name + ": " + i);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. This line of code will display the String
written inside the parenthesis. */
Thread.sleep(200);
}
49
} catch (InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println(name + " interrupted.");
// If any exception occurs then this line of code will display the string written inside parenthesis.
}
System.out.println(name + " exiting.");
// This line of code will display the String written inside the parenthesis.
}
}
class SuspendResume {
/* this line contains a keyword class that shows that a class is going to start and
SuspendResume is the name of this class. Opening curly brace { shows that form here a class’
definition is going to begin */
// Your program begin with a call to main.
public static void main(String args[]) {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
// 2 new objects of class are initialized and declared
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
50
Thread.sleep(1000);
ob1.t.suspend(); // obj1 is suspended
System.out.println("Suspending thread One");
// This line of code will display the String written inside the parenthesis.
Thread.sleep(1000);
ob1.t.resume(); //// obj1 is resumed
System.out.println("Resuming thread One");
// This line of code will display the String written inside the parenthesis.
ob2.t.suspend(); // obj2 is suspended
System.out.println("Suspending thread Two");
// This line of code will display the String written inside the parenthesis.
Thread.sleep(1000);
// thread sleeps for the given interval of time
ob2.t.resume(); //// obj1 is resumes
System.out.println("Resuming thread Two");
// This line of code will display the String written inside the parenthesis.
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
// If any exception occurs then this line of code will display that Main thread interrupted.
}
// wait for threads to finish
try {
/* From this line of code the try block starts. Opening delimiter shows that try block’s definition
is going to start. This block will try to interpret what is written inside it. Otherwise exception will
occur that will be caught by the catch block, written right after the try block*/
System.out.println("Waiting for threads to finish.");
51
// This line of code will display the String written inside the parenthesis.
ob1.t.join();
ob2.t.join();
// here join() method is called that waits for a thread to finish
} catch (InterruptedException e) {
// catch block catches exception if it occurs and stored it in its object e
System.out.println("Main thread Interrupted");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. If any exception occurs then this line of code
will display that Main thread interrupted */
} // closing curly brace } is used to close the definition of catch block
System.out.println("Main thread exiting.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. It will print the String written inside it in
double quotes*/
}
}
52
Output:
Discussion:
The demo contains suspend() and resume() methods. These methods are defined by Thread to
pause and restart the execution of thread. This program creates 2 objects ob1 and ob2 and displays each’
thread with an interval or pause by suspend() and sleep() methods. It also resumes the working of both the
53
objects and then displays that both the threads are exiting including main thread. The thread class also
defines a method called stop() that stops a thread. Once a thread has been stopped, it cannot be restarted
using resume() method.
Program 86:
Write a program that uses buffer reader to read the characters.
Solution:
// Use a BufferedReader to read characters from the console.
import java.io.*;
/* first of all import a java.io package which is knows as basic input output package. It is a
package that handles byte streams like input stream, output stream etc*/
class BRRead {
/* this line contains a keyword class that shows that a class is going to start and BRRead is the
name of this class. Opening curly brace { shows that form here a class’ definition is going to
begin */
public static void main(String args[])
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
throws IOException{
char c; // character c is declared
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
/* use to create a character stream Br is a character based stream that is linked to the console
through system.in and buffer reader supports a buffer input stream. System.in is a line buffered
by default*/
System.out.println("Enter characters, 'q' to quit.");
54
/* read characters. System is a built in function used to give access to the system. Out is used for
the output. Println is used to print or display the string passed to it & ln is used to goto the next
line. Semicolon is used to terminate the statement/line */
Do { // loop starts
c = (char) br.read();
// characters will be read from the console and stored in c
System.out.println(c);
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. // This line of code will display the String
written inside the parenthesis. */
}
while(c != 'q');
// it will give output until we press q ( loop ends)
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
55
Output:
Discussion:
This demo first wants the user to type a string then reads a character from the console
using BufferedReader and read() methods. Each time that read() method is called, it reads a
character from the input stream and returns it one by one. It returns –1 when the end of the
stream is encountered. No input is passed to the program until we press enter. This program
continues it’s working until user type q to quit.
Program 87:
write a program that reads the string from console.
Solution:
// Read a string from console using a BufferedReader.
import java.io.*;
/* first of all import a java.io package which is knows as basic input output package. It is a
package that handles byte streams like input stream, output stream etc*/
class BRReadLines {
56
/* this line contains a keyword class that shows that a class is going to start and BRReadLines is
the name of this class. Opening curly brace { shows that form here a class’ definition is going to
begin */
public static void main(String args[]) throws IOException{
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin and throwsIOException
means that this code can throw exception*/
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
/* use to create a character stream Br is a character based stream that is linked to the console
through system.in and buffer reader supports a buffer input stream. System.in is a line buffered
by default*/
String str; // a variable str of type string is declared
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. // These lines of code will display the String
written inside the parenthesis. */
do { // loop starts
str = br.readLine();
/* br is the instance of BufferReader that by using dot operator calls a readLine() method and
stores it in the variable str of type string */
System.out.println(str);
// This line of code will display the String written inside the parenthesis.
} while(!str.equals("stop"));
57
// when the entered string will be equal to stop then the program quit
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
Output:
Discussion:
In this demo BufferedReader()and inputSteamReader() methods are used that first wants
the user to type a string then they read it and dislay is again. To read a string from the console
readLine() method is used that is a member of the BufferedReader class. The process
continues until the user type stop.
Program 88:
Write a program that reads upto 100 lines or until you enter stop. It
uses buffer reader to read from the console.
Solution:
// A tiny editor.
import java.io.*;
58
/* first of all import a java.io package which is knows as basic input output package. It is a
package that handles byte streams like input stream, output stream etc*/
class TinyEdit {
/* this line contains a keyword class that shows that a class is going to start and TinyEdit is the
name of this class. Opening curly brace { shows that form here a class’ definition is going to
begin */
public static void main(String args[]) throws IOException {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin and throwsIOException
means that this code can throw exception */
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
/* use to create a character stream Br is a character based stream that is linked to the console
through system.in and buffer reader supports a buffer input stream. System.in is a line buffered
by default*/
String str[] = new String[100];
// a string str of size 100 is declared and initialized here.
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
/* System is a built in function used to give access to the system. Out is used for the output.
Println is used to print or display the string passed to it & ln is used to goto the next line.
Semicolon is used to terminate the statement/line. These line of code will display the String
written inside the parenthesis. */
for(int i=0; i<100; i++) {
/*a for loop is declared here it contains three parts initialization that initializes n to 0, condition
i.e n is less than 100, iteration i.e increment of n. Firstly loop initialize n to 0 and then it will
check the condition that either it is true or not, if it is true then the next statement will be
59
compiled, after that control/system will pass to the iteration process then it will check the
condition if it is fulfilled then the statement given below will be executed again i.e it will go on
increasing the value of n by 1 until the condition is not satisfied*/
str[i] = br.readLine();
/* br is the instance of BufferReader that by using dot operator calls a readLine() method and
stores it in the variable str[i] of type string */
if(str[i].equals("stop")) break;
// if the given condition is satisfied then it will break
}
System.out.println("nHere is your file:");
// This line of code will display the String written inside the parenthesis.
for(int i=0; i<100; i++) {
/*a for loop is declared here it contains three parts initialization that initializes n to 0, condition
i.e n is less than 100, iteration i.e increment of n. Firstly loop initialize n to 0 and then it will
check the condition that either it is true or not, if it is true then the next statement will be
compiled, after that control/system will pass to the iteration process then it will check the
condition if it is fulfilled then the statement given below will be executed again i.e it will go on
increasing the value of n by 1 until the condition is not satisfied*/
if(str[i].equals("stop")) break;
// if the given condition is satisfied then it will break
System.out.println(str[i]);
// This line of code will display the String written inside the parenthesis.
}
}// closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
60
Output:
Discussion:
In this demo using BufferedReader() and fileInputStreamReader() the data written on the
console will be displayed again on it. BufferedReader() method reads the text from the console. This
demo first wants us to write the lines of the text then if we want to stop then wants us to type stop just in
the same way as it is mentione on console then the compiler compares it to the string already declared to
“stop” if it matches then it will display what you entered/ type. It will read up to 100 lines or until we
enter stop.
Program 89:
write a program that uses Print Writer to handle the console.
Solution:
// Demonstrate PrintWriter
import java.io.*;
/* first of all import a java.io package which is knows as basic input output package. It is a
package that handles byte streams like input stream, output stream etc*/
public class PrintWriterDemo {
61
/* this line contains a keyword class that shows that a class is going to start and
PrintWriterDemo is the name of this class. Opening curly brace { shows that form here a
class’ definition is going to begin */
public static void main(String args[]) {
/*this line of code shows that public is an access specifier that allows a programmer to control
its visibility or access, means this class is accessible out of the class in which it is declared i.e
anyone publically can access it. Static is a keyword that allows the main() method to be execute
without instantiating an instance of that class. Void means this main() method has no return
type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly
brace { shows that form here the method’s definition is going to begin */
PrintWriter pw = new PrintWriter(System.out, true);
// printWriter is used to write to the console. system.out is used for the output stream and flush
the stream after each new line
pw.println("This is a string"); // display this text
int i = -7; // a local variable i of type int
pw.println(i); // displays i on the command prompt
double d = 4.5e-7; // a local variable d of type double
pw.println(d); // displays d on the console
} // closing curly brace } is used to close the definition of main() method
} // closing curly brace } is used to close the definition of class
Output:
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining
JAVA Manual remaining

Contenu connexe

Tendances

Tr 3749 -net_app_storage_best_practices_for_v_mware_vsphere,_dec_11
Tr 3749 -net_app_storage_best_practices_for_v_mware_vsphere,_dec_11Tr 3749 -net_app_storage_best_practices_for_v_mware_vsphere,_dec_11
Tr 3749 -net_app_storage_best_practices_for_v_mware_vsphere,_dec_11
Accenture
 
CAST_CBOK_Ver_6-2 2010.09.17
CAST_CBOK_Ver_6-2 2010.09.17CAST_CBOK_Ver_6-2 2010.09.17
CAST_CBOK_Ver_6-2 2010.09.17
Tasha Howle
 
Qtp Tutorial
Qtp TutorialQtp Tutorial
Qtp Tutorial
seshuu
 
100PercentPureJavaCookbook-4_1_1
100PercentPureJavaCookbook-4_1_1100PercentPureJavaCookbook-4_1_1
100PercentPureJavaCookbook-4_1_1
AbrarMoiz
 
Product description vital qip next generation v7 2_en_feb09(1)
Product description vital qip next generation v7 2_en_feb09(1)Product description vital qip next generation v7 2_en_feb09(1)
Product description vital qip next generation v7 2_en_feb09(1)
Roy Muy Golfo
 
Q T P Tutorial
Q T P  TutorialQ T P  Tutorial
Q T P Tutorial
rosereddy
 

Tendances (19)

Auditoría de TrueCrypt: Informe final fase II
Auditoría de TrueCrypt: Informe final fase IIAuditoría de TrueCrypt: Informe final fase II
Auditoría de TrueCrypt: Informe final fase II
 
Fax for-asterisk-manual
Fax for-asterisk-manualFax for-asterisk-manual
Fax for-asterisk-manual
 
Tr 3749 -net_app_storage_best_practices_for_v_mware_vsphere,_dec_11
Tr 3749 -net_app_storage_best_practices_for_v_mware_vsphere,_dec_11Tr 3749 -net_app_storage_best_practices_for_v_mware_vsphere,_dec_11
Tr 3749 -net_app_storage_best_practices_for_v_mware_vsphere,_dec_11
 
Recommend_Cases
Recommend_CasesRecommend_Cases
Recommend_Cases
 
CSTE_CBOK_V6-2
CSTE_CBOK_V6-2CSTE_CBOK_V6-2
CSTE_CBOK_V6-2
 
CAST_CBOK_Ver_6-2 2010.09.17
CAST_CBOK_Ver_6-2 2010.09.17CAST_CBOK_Ver_6-2 2010.09.17
CAST_CBOK_Ver_6-2 2010.09.17
 
Qtp Tutorial
Qtp TutorialQtp Tutorial
Qtp Tutorial
 
Cs tocpp a-somewhatshortguide
Cs tocpp a-somewhatshortguideCs tocpp a-somewhatshortguide
Cs tocpp a-somewhatshortguide
 
100PercentPureJavaCookbook-4_1_1
100PercentPureJavaCookbook-4_1_1100PercentPureJavaCookbook-4_1_1
100PercentPureJavaCookbook-4_1_1
 
Akka java
Akka javaAkka java
Akka java
 
Product description vital qip next generation v7 2_en_feb09(1)
Product description vital qip next generation v7 2_en_feb09(1)Product description vital qip next generation v7 2_en_feb09(1)
Product description vital qip next generation v7 2_en_feb09(1)
 
Pandora FMS: Mysql Server Monitoring
Pandora FMS: Mysql Server MonitoringPandora FMS: Mysql Server Monitoring
Pandora FMS: Mysql Server Monitoring
 
Specification of the Linked Media Layer
Specification of the Linked Media LayerSpecification of the Linked Media Layer
Specification of the Linked Media Layer
 
Sap testing tutorial
Sap testing tutorialSap testing tutorial
Sap testing tutorial
 
Lesson 5...Guide
Lesson 5...GuideLesson 5...Guide
Lesson 5...Guide
 
Q T P Tutorial
Q T P  TutorialQ T P  Tutorial
Q T P Tutorial
 
Windowstweaksguide updated
Windowstweaksguide updatedWindowstweaksguide updated
Windowstweaksguide updated
 
Pervasive Video in the Enterprise
Pervasive Video in the EnterprisePervasive Video in the Enterprise
Pervasive Video in the Enterprise
 
Selenium documentation 1.0
Selenium documentation 1.0Selenium documentation 1.0
Selenium documentation 1.0
 

En vedette

En vedette (20)

Digital logic and design's Lab 4 nand
Digital logic and design's Lab 4 nandDigital logic and design's Lab 4 nand
Digital logic and design's Lab 4 nand
 
Summary of Simultaneous Multithreading: Maximizing On-Chip Parallelism
Summary of Simultaneous Multithreading: Maximizing On-Chip ParallelismSummary of Simultaneous Multithreading: Maximizing On-Chip Parallelism
Summary of Simultaneous Multithreading: Maximizing On-Chip Parallelism
 
Digital logic and design's Lab 3
Digital logic and design's Lab 3Digital logic and design's Lab 3
Digital logic and design's Lab 3
 
Prefix and suffix of open gl
Prefix and suffix of open glPrefix and suffix of open gl
Prefix and suffix of open gl
 
Linear combination of vector
Linear combination of vectorLinear combination of vector
Linear combination of vector
 
Scaling
ScalingScaling
Scaling
 
Cohen sutherland algorithm
Cohen sutherland algorithmCohen sutherland algorithm
Cohen sutherland algorithm
 
Javadocx j option pane
Javadocx j option paneJavadocx j option pane
Javadocx j option pane
 
Applications of Image Processing
Applications of Image ProcessingApplications of Image Processing
Applications of Image Processing
 
Raster images (assignment)
Raster images (assignment)Raster images (assignment)
Raster images (assignment)
 
Templates
TemplatesTemplates
Templates
 
Tomasulo Algorithm
Tomasulo AlgorithmTomasulo Algorithm
Tomasulo Algorithm
 
Chapter 4: Lexical & Syntax Analysis (Programming Exercises)
Chapter 4: Lexical & Syntax Analysis (Programming Exercises)Chapter 4: Lexical & Syntax Analysis (Programming Exercises)
Chapter 4: Lexical & Syntax Analysis (Programming Exercises)
 
Mission statement and Vision statement of 3 Different Companies
Mission statement and Vision statement of 3 Different CompaniesMission statement and Vision statement of 3 Different Companies
Mission statement and Vision statement of 3 Different Companies
 
Implementation & Challenges of IPv6
Implementation & Challenges of IPv6Implementation & Challenges of IPv6
Implementation & Challenges of IPv6
 
IPv6 Implementation challenges
IPv6 Implementation challengesIPv6 Implementation challenges
IPv6 Implementation challenges
 
DLDLab 8 half adder
DLDLab 8 half adderDLDLab 8 half adder
DLDLab 8 half adder
 
Graphic display devices
Graphic display devicesGraphic display devices
Graphic display devices
 
Memory Hierarchy Design, Basics, Cache Optimization, Address Translation
Memory Hierarchy Design, Basics, Cache Optimization, Address TranslationMemory Hierarchy Design, Basics, Cache Optimization, Address Translation
Memory Hierarchy Design, Basics, Cache Optimization, Address Translation
 
Hacking and Hackers
Hacking and HackersHacking and Hackers
Hacking and Hackers
 

Similaire à JAVA Manual remaining

46600726 vijeo-quick-start-tutorial-v710
46600726 vijeo-quick-start-tutorial-v71046600726 vijeo-quick-start-tutorial-v710
46600726 vijeo-quick-start-tutorial-v710
croyf
 
Managing sap upgrade_projects
Managing sap upgrade_projectsManaging sap upgrade_projects
Managing sap upgrade_projects
Kishore Kumar
 
Primavera P6 User guide.pdf
Primavera P6 User guide.pdfPrimavera P6 User guide.pdf
Primavera P6 User guide.pdf
ssuseraaebbd
 
bkremer-report-final
bkremer-report-finalbkremer-report-final
bkremer-report-final
Ben Kremer
 

Similaire à JAVA Manual remaining (20)

Qtp tutorial
Qtp tutorialQtp tutorial
Qtp tutorial
 
Programming
ProgrammingProgramming
Programming
 
100 JAVA Programs-1.pdf
100 JAVA Programs-1.pdf100 JAVA Programs-1.pdf
100 JAVA Programs-1.pdf
 
Sap hana server installation guide
Sap hana server installation guideSap hana server installation guide
Sap hana server installation guide
 
Apache Maven
Apache MavenApache Maven
Apache Maven
 
Saphanaadministrationguide
SaphanaadministrationguideSaphanaadministrationguide
Saphanaadministrationguide
 
Tutorial ceph-2
Tutorial ceph-2Tutorial ceph-2
Tutorial ceph-2
 
Cpt5 manual
Cpt5 manualCpt5 manual
Cpt5 manual
 
Learn python the right way
Learn python the right wayLearn python the right way
Learn python the right way
 
Open edX Building and Running a Course
Open edX Building and Running a CourseOpen edX Building and Running a Course
Open edX Building and Running a Course
 
Qtp user-guide
Qtp user-guideQtp user-guide
Qtp user-guide
 
Solution master guide.pdf
Solution master guide.pdfSolution master guide.pdf
Solution master guide.pdf
 
Cake php cookbook
Cake php cookbookCake php cookbook
Cake php cookbook
 
46600726 vijeo-quick-start-tutorial-v710
46600726 vijeo-quick-start-tutorial-v71046600726 vijeo-quick-start-tutorial-v710
46600726 vijeo-quick-start-tutorial-v710
 
Managing sap upgrade_projects
Managing sap upgrade_projectsManaging sap upgrade_projects
Managing sap upgrade_projects
 
Primavera P6 User guide.pdf
Primavera P6 User guide.pdfPrimavera P6 User guide.pdf
Primavera P6 User guide.pdf
 
Drools expert-docs
Drools expert-docsDrools expert-docs
Drools expert-docs
 
TEST UPLOAD
TEST UPLOADTEST UPLOAD
TEST UPLOAD
 
sum2_abap_unix_hana.pdf
sum2_abap_unix_hana.pdfsum2_abap_unix_hana.pdf
sum2_abap_unix_hana.pdf
 
bkremer-report-final
bkremer-report-finalbkremer-report-final
bkremer-report-final
 

Plus de Farwa Ansari

Plus de Farwa Ansari (9)

Energy Harvesting Techniques in Wireless Sensor Networks – A Survey
Energy Harvesting Techniques in Wireless Sensor Networks – A SurveyEnergy Harvesting Techniques in Wireless Sensor Networks – A Survey
Energy Harvesting Techniques in Wireless Sensor Networks – A Survey
 
Micro-services architecture
Micro-services architectureMicro-services architecture
Micro-services architecture
 
Software Design Patterns - An Overview
Software Design Patterns - An OverviewSoftware Design Patterns - An Overview
Software Design Patterns - An Overview
 
Optimizing the memory management of a virtual machine monitor on a NUMA syste...
Optimizing the memory management of a virtual machine monitor on a NUMA syste...Optimizing the memory management of a virtual machine monitor on a NUMA syste...
Optimizing the memory management of a virtual machine monitor on a NUMA syste...
 
Fault Tolerance Typed Assembly Language - A graphical overview
Fault Tolerance Typed Assembly Language - A graphical overviewFault Tolerance Typed Assembly Language - A graphical overview
Fault Tolerance Typed Assembly Language - A graphical overview
 
Comparative Analysis of Face Recognition Methodologies and Techniques
Comparative Analysis of Face Recognition Methodologies and TechniquesComparative Analysis of Face Recognition Methodologies and Techniques
Comparative Analysis of Face Recognition Methodologies and Techniques
 
Chapter 5: Names, Bindings and Scopes (review Questions and Problem Set)
Chapter 5: Names, Bindings and Scopes (review Questions and Problem Set)Chapter 5: Names, Bindings and Scopes (review Questions and Problem Set)
Chapter 5: Names, Bindings and Scopes (review Questions and Problem Set)
 
Business plan of a software house
Business plan of a software houseBusiness plan of a software house
Business plan of a software house
 
Dld (lab 1 & 2)
Dld (lab 1 & 2)Dld (lab 1 & 2)
Dld (lab 1 & 2)
 

Dernier

Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Dernier (20)

VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 

JAVA Manual remaining

  • 1. Remaining JAVA manual Remaining manual of JAVA 2 F. Ansari 8/10/2014
  • 2. 2 Contents Program 75:...................................................................................................................................................6 Solution:........................................................................................................................................................6 Output: ..........................................................................................................................................................8 Discussion:....................................................................................................................................................8 Program 76:...................................................................................................................................................9 Solution:........................................................................................................................................................9 Output: ........................................................................................................................................................13 Discussion:..................................................................................................................................................13 Program 77:.................................................................................................................................................14 Solution:......................................................................................................................................................14 Output: ........................................................................................................................................................18 Discussion:..................................................................................................................................................18 Program 78:.................................................................................................................................................18 Solution:......................................................................................................................................................18 Output: ........................................................................................................................................................22 Discussion:..................................................................................................................................................22 Program 79:.................................................................................................................................................23 Solution:......................................................................................................................................................23 Output: ........................................................................................................................................................27 Discussion:..................................................................................................................................................27 Program 80:.................................................................................................................................................27 Solution:......................................................................................................................................................27 Output: ........................................................................................................................................................30 Discussion:..................................................................................................................................................31 Program 81:.................................................................................................................................................31 Solution:......................................................................................................................................................31 Output: ........................................................................................................................................................34 Discussion:..................................................................................................................................................34 Program 82:.................................................................................................................................................35 Solution:......................................................................................................................................................35 Output: ........................................................................................................................................................38
  • 3. 3 Discussion:..................................................................................................................................................38 Program 83:.................................................................................................................................................38 Solution:......................................................................................................................................................38 Output: ........................................................................................................................................................42 Discussion:..................................................................................................................................................43 Program 84:.................................................................................................................................................43 Solution:......................................................................................................................................................43 Output: ........................................................................................................................................................47 Discussion:..................................................................................................................................................47 Program 85:.................................................................................................................................................47 Solution:......................................................................................................................................................47 Output: ........................................................................................................................................................52 Discussion:..................................................................................................................................................52 Program 86:.................................................................................................................................................53 Solution:......................................................................................................................................................53 Output: ........................................................................................................................................................55 Discussion:..................................................................................................................................................55 Program 87:.................................................................................................................................................55 Solution:......................................................................................................................................................55 Output: ........................................................................................................................................................57 Discussion:..................................................................................................................................................57 Program 88:.................................................................................................................................................57 Solution:......................................................................................................................................................57 Output: ........................................................................................................................................................60 Discussion:..................................................................................................................................................60 Program 89:.................................................................................................................................................60 Solution:......................................................................................................................................................60 Output: ........................................................................................................................................................61 Discussion:..................................................................................................................................................62 Program 90:.................................................................................................................................................62 Solution:......................................................................................................................................................62 Output: ........................................................................................................................................................64
  • 4. 4 Discussion:..................................................................................................................................................64 Program 91:.................................................................................................................................................65 Solution:......................................................................................................................................................65 Output: ........................................................................................................................................................68 Discussion:..................................................................................................................................................68 Program 92:.................................................................................................................................................68 Solution:......................................................................................................................................................68 Output: ........................................................................................................................................................71 Discussion:..................................................................................................................................................71 Program 93:.................................................................................................................................................71 Solution:......................................................................................................................................................71 Output: ........................................................................................................................................................75 Discussion:..................................................................................................................................................75 Program94:..................................................................................................................................................75 Solution:......................................................................................................................................................75 Output: ........................................................................................................................................................78 Discussion:..................................................................................................................................................78 Program 95:.................................................................................................................................................78 Solution:......................................................................................................................................................78 Output: ........................................................................................................................................................81 Discussion:..................................................................................................................................................81 Program 96:.................................................................................................................................................81 Solution:......................................................................................................................................................81 Output: ........................................................................................................................................................84 Discussion:..................................................................................................................................................84 Program 97:.................................................................................................................................................85 Solution:......................................................................................................................................................85 Output: ........................................................................................................................................................87 Discussion:..................................................................................................................................................87 Program 98:.................................................................................................................................................88 Solution:......................................................................................................................................................88 Output: ........................................................................................................................................................90
  • 5. 5 Discussion:..................................................................................................................................................90 Program 99:.................................................................................................................................................90 Solution:......................................................................................................................................................90 Output: ........................................................................................................................................................92 Discussion:..................................................................................................................................................92 Program 100:...............................................................................................................................................93 Solution:......................................................................................................................................................93 Output: ........................................................................................................................................................96 Discussion:..................................................................................................................................................97 Program 101:...............................................................................................................................................97 Solution:......................................................................................................................................................97 Output: ........................................................................................................................................................98 Discussion:..................................................................................................................................................99 Program 102:...............................................................................................................................................99 Solution:......................................................................................................................................................99 HTML Code:.......................................................................................................................................100 Output: ......................................................................................................................................................101 Discussion:................................................................................................................................................101 Program 103:.............................................................................................................................................102 Solution:....................................................................................................................................................102 HTML Code:.....................................................................................................................................102 Output: ......................................................................................................................................................103 Discussion:................................................................................................................................................103 Program 104:.............................................................................................................................................103 Solution:....................................................................................................................................................103 HTML Code:.....................................................................................................................................104 Output: ......................................................................................................................................................105 Discussion:................................................................................................................................................105
  • 6. 6 Program 75: Write a code using the concept of multithreading that controls the main thread. Solution: // controlling the main Thread. class CurrentThreadDemo { /* this line contains a keyword class that shows that a class is going to start and CurrentThreadDemo is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ // Your program begin with a call to main. public static void main(String args[]){ /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ Thread t = Thread.currentThread(); // a thread defines a separate path of execution & here an object/local variable of thread is declared and initialized System.out.println("Current thread: " + t); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will print the current thread that is stored in the object of thread t */ // change the name of the thread t.setName("My Thread"); /* In this line of code the name of the Thread is changed by calling a built in function setName() that set the name by taking a String as an argument inside the paranthesis.*/ System.out.println("After name change: " + t);
  • 7. 7 /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will print the thread after its name changed that is stored in the object t of thread */ try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ for(int n = 5; n > 0; n--) { /*a for loop is declared here it contains three parts initialization that initializes n to 5, condition i.e n is greater than 0, iteration i.e decrement of n. Firstly loop initialize n to 5 and then it will check the condition that either it is true or not, if it is true then the next statement will be compiled, after that control/system will pass to the iteration process then it will check the condition if it is fulfilled then the statement given below will be executed again i.e it will go on decreasing the value of n by 1 until the condition is not satisfied*/ System.out.println(n); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. It will display the value of n*/ Thread.sleep(1000); // thread will sleep/paused for the time given in parenthesis } // closing curly brace } is used to close the definition of for loop } catch (InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println("Main thread interrupted"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. If any exception occurs then this line of code will display that Main thread interrupted */ } // closing curly brace } is used to close the definition of catch block } // closing curly brace } is used to close the definition of main() method
  • 8. 8 } // closing curly brace } is used to close the definition of class Output: Discussion: The program contains a reference to the current thread, obtained by calling currentThread( ), and this reference is stored in the local variable t. Then the program displays information about the thread. The program then calls setName( ) method to change the name of the thread. Information about the thread is then displayed again. Then a loop starts from five and it sleeps or pauses for one second between each line. Then the try/catch block starts after this loop. If the sleep( ) method in Thread will throw an InterruptedException then it will be caught and displayed by the catch block.
  • 9. 9 Program 76: Using the concept of multithreading write a code that implements runnable & will not run until the start() method written within thread is called. Solution: // Create a second thread. class NewThread implements Runnable { /* this line contains a keyword class that shows that a class is going to start and NewThread is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin. It implements Runnable an abstract class */ Thread t; // t is the local variable or an object of Thread is initialized here and stores. NewThread() { // Constructor of NewThread() class. Inside NewThread’s constructor, a new Thread object is created t = new Thread(this, "Demo Thread"); // Create a new, second thread System.out.println("Child thread: " + t); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { /* public is a keyword which means that this method is publically accessible, void means that it has no return type, run() is the abstract method of abstract class Runnable and it is implemented here, Opening Curly Brace { means that the method’s def. is going to start. */
  • 10. 10 try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ for(int i = 5; i > 0; i--) { /*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will check the condition that either it is true or not, if it is true then the next statement will be compiled, after that control/system will pass to the iteration process then it will check the condition if it is fulfilled then the statement given below will be executed again i.e it will go on increasing the value of i by 1 until the condition is not satisfied*/ System.out.println("Child Thread: " + i); // This line of code will display the String written inside the parenthesis for ith time. Thread.sleep(500); // thread will sleep/paused for the time given in parenthesis } // closing curly brace } is used to close the definition of for loop. } catch (InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println("Child interrupted."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis if any exception occurs. */ } System.out.println("Exiting child thread."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */
  • 11. 11 } // closing curly brace } is used to close the definition of run() method } // closing curly brace } is used to close the definition of class class ThreadDemo { /* this line contains a keyword class that shows that a class is going to start and ThreadDemo is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ // Your program begin with a call to main. public static void main(String args[]) { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ new NewThread(); // create a new thread try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ for(int i = 5; i > 0; i--) { /*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will check the condition that either it is true or not, if it is true then the next statement will be compiled, after that control/system will pass to the iteration process then it will check the condition if it is fulfilled then the statement given below will be executed again i.e it will go on increasing the value of i by 1 until the condition is not satisfied*/ System.out.println("Main Thread: " + i); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis.*/ Thread.sleep(1000);
  • 12. 12 // thread will sleep/paused for the time given in parenthesis } } catch (InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println("Main thread interrupted."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis if any exception occurs. */ } System.out.println("Main thread exiting."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class
  • 13. 13 Output: Discussion: In this program the first thread is used to call the run() method using this object. Then start( ) is called, which starts the thread at the run( ) method. This causes the thread’s for loop to begin. After calling start( ), NewThread’s constructor returns to main( ). When the main thread starts, it enters its for loop. Both threads continue running, until their loops finish. Hence they display the output.
  • 14. 14 Program 77: Write a code using multithreading concept by extending Thread class. Solution: // Create a second thread by extending Thread class NewThread extends Thread { /* this line contains a keyword class that shows that a class is going to start and NewThread is the name of this class and this class extends Thread. Opening curly brace { shows that form here a class’ definition is going to begin */ NewThread() { // Constructor of NewThread() class. Inside NewThread’s constructor, a new Thread object is created super("Demo Thread"); /* the call to super( ) inside NewThread invokes the following form of the Thread constructor i.e public Thread(String threadName). Here, threadName specifies the name of the thread.*/ System.out.println("Child thread: " + this); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will print the current thread that is stored in the this keyword. */ start(); // Start the thread } // This is the entry point for the second thread. public void run() { /* public is a keyword which means that this method is publically accessible, void means that it has no return type, run() is the abstract method of abstract class Runnable and it is implemented here, Opening Curly Brace { means that the method’s def. is going to start. */ try {
  • 15. 15 /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ for(int i = 5; i > 0; i--) { /*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will check the condition that either it is true or not, if it is true then the next statement will be compiled, after that control/system will pass to the iteration process then it will check the condition if it is fulfilled then the statement given below will be executed again i.e it will go on increasing the value of i by 1 until the condition is not satisfied*/ System.out.println("Child Thread: " + i); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will print what is written inside it. */ Thread.sleep(500); // thread will sleep/paused for the time given in parenthesis } } catch (InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println("Child interrupted."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will print what is written inside it if any exception occurs and caught by catch block.*/ } System.out.println("Exiting child thread."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will print the statement written inside it. */
  • 16. 16 } } class ExtendThread { /* this line contains a keyword class that shows that a class is going to start and ExtendThread is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ public static void main(String args[]) { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ new NewThread(); // create a new thread try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ for(int i = 5; i > 0; i--) { /*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will check the condition that either it is true or not, if it is true then the next statement will be compiled, after that control/system will pass to the iteration process then it will check the condition if it is fulfilled then the statement given below will be executed again i.e it will go on increasing the value of i by 1 until the condition is not satisfied*/ System.out.println("Main Thread: " + i); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ Thread.sleep(1000); }
  • 17. 17 } catch (InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println("Main thread interrupted."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis if any exception occurs and caught by catch block. */ } System.out.println("Main thread exiting."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class
  • 18. 18 Output: Discussion: This program generates the same output as the above program generates. The thread is created by instantiating an object of NewThread, which is derived from Thread. Notice the call to super( ) inside NewThread. This runs the Thread constructor and super performs the erasing behavior. Program 78: Write a code using multithreading concept that creates multiple threads Solution: // Create multiple threads. class NewThread implements Runnable {
  • 19. 19 /* this line contains a keyword class that shows that a class is going to start and NewThread is the name of this class and it implements an abstract class Runnable(). Opening curly brace { shows that form here a class’ definition is going to begin */ String name; // name of thread Thread t; // t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s constructor, a new Thread object is created NewThread(String threadname) { // An argument Constructor of NewThread() class. Inside NewThread’s constructor, a new Thread object is created name = threadname; // String is initialized here. t = new Thread(this, name); // Create a new, second thread. t is initialized here and reference to the name is stored in it. System.out.println("New thread: " + t); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will print the new thread that is stored in the object t of thread */ t.start(); // Start the thread } // This is the entry point for thread. public void run() { /* public is a keyword which means that this method is publically accessible, void means that it has no return type, run() is the abstract method of abstract class Runnable and it is implemented here, Opening Curly Brace { means that the method’s def. is going to start. */ try {
  • 20. 20 /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ for(int i = 5; i > 0; i--) { /*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will check the condition that either it is true or not, if it is true then the next statement will be compiled, after that control/system will pass to the iteration process then it will check the condition if it is fulfilled then the statement given below will be executed again i.e it will go on increasing the value of i by 1 until the condition is not satisfied*/ System.out.println(name + ": " + i); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ Thread.sleep(1000); // thread will sleep/paused for the time given in parenthesis } } catch (InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println(name + "Interrupted"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ } System.out.println(name + " exiting."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis.*/
  • 21. 21 } } class MultiThreadDemo { // Your program begin with a call to main. public static void main(String args[]) { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three"); // new threads started here try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ // wait for other threads to end Thread.sleep(10000); // thread will sleep/paused for the time given in parenthesis } catch (InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println("Main thread Interrupted"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. If any exception occurs then this line of code will display that Main thread interrupted */
  • 22. 22 } System.out.println("Main thread exiting."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class Output: Discussion: This program once started, all three new/ child threads start executing/ running. Notice the call to sleep(10000) in main( ). This causes the main thread to sleep for ten seconds and ensures that it will finish last.
  • 23. 23 Program 79: Write a code that demonstrate thread priorities Solution: // Demonstrate thread priorities. class clicker implements Runnable { /* this line contains a keyword class that shows that a class is going to start and clicker is the name of this class and it implements Runnable an abstract class. Opening curly brace { shows that form here a class’ definition is going to begin */ long click = 0; // local variable to type ling initialized to 0 Thread t; // t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s constructor, a new Thread object is created private volatile boolean running = true; /* here a private volatile Boolean variable is declared and initialized. Private means can’t b accessible outside the class and volatile variable means the variable whose value is always held in main memory so that it can be accessed by different threads. */ public clicker(int p) { // An argument Constructor of Clicker() class. t = new Thread(this); // t is initialized here t.setPriority(p); // priority is been set here calling setPriority() function } public void run() { /* public is a keyword which means that this method is publically accessible, void means that it has no return type, run() is the abstract method of abstract class Runnable and it is implemented here, Opening Curly Brace { means that the method’s def. is going to start. */ while (running) {
  • 24. 24 click++; } // if running then click will keep on incrementing } public void stop() { ///* public is a keyword which means that this method is publically accessible, void means that it has no return type, stop() is the method to stop the running thread. Opening Curly Brace { means that the method’s def. is going to start. */ running = false; // to stop we will make running false } public void start() { t.start(); } // this method will start the thread } class HiLoPri { /* this line contains a keyword class that shows that a class is going to start and HiLoPri is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ // Your program begin with a call to main. public static void main(String args[]) { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */
  • 25. 25 Thread.currentThread().setPriority(Thread.MAX_PRIORITY); clicker hi = new clicker(Thread.NORM_PRIORITY + 2); clicker lo = new clicker(Thread.NORM_PRIORITY - 2); // here 2 objects of class clicker are created and instantiated i.e hi, lo and both are set to default priority using NORM_PRIORITY but by +2 & -2 hi will b of high n lo will b of low priority lo.start(); hi.start(); // here both objects’s working starts using start() methd try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ Thread.sleep(10000); // thread will sleep/paused for the time given in parenthesis } catch (InterruptedException e) { System.out.println("Main thread interrupted."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis if any exception occurs. */ } lo.stop(); hi.stop(); // here the working of both the instances of class will stop by calling stop() method // Wait for child threads to terminate. try {
  • 26. 26 /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ hi.t.join(); lo.t.join(); // here join() method is called that waits for a thread to finish } catch (InterruptedException e) { System.out.println("InterruptedException caught"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis if any exception occurs.*/ } System.out.println("Low-priority thread: " + lo.click); System.out.println("High-priority thread: " + hi.click); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. These lines of code will display the Strings written inside the parenthesis. */ } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class
  • 27. 27 Output: Discussion: Thread priorities are used by the thread scheduler to decide when each thread is allowed to run. Higher priority threads get more time then lower priority threads. To set the thread priority setPriority() method is used which is a member of Thread. In this program an instance of thread is initialized and setPriority() method is called through it. Then run(), stop() and start() method is called. Then main method is declared in which the class instantiated. Then a join() method is called with the class’ instances that method waits for a thread to finish. Then high level and low level threads are stored in hi and lo objects respectively and then displayed as above. Program 80: Write a code that will not synchronized Solution: // This program is not synchronized. class Callme { /* this line contains a keyword class that shows that a class is going to start and Callme is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ void call(String msg) { System.out.print("[" + msg); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line.
  • 28. 28 Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. If any exception occurs then this line of code will display Interrupted */ } System.out.println("]"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ } } class Caller implements Runnable { String msg; Callme target; // instance of class Thread t; // t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s constructor, a new Thread object is created public Caller(Callme targ, String s) { target = targ;
  • 29. 29 msg = s; t = new Thread(this); // t is initializes t.start(); // thread starts } public void run() { /* public is a keyword which means that this method is publically accessible, void means that it has no return type, run() is the abstract method of abstract class Runnable and it is implemented here, Opening Curly Brace { means that the method’s def. is going to start. */ target.call(msg); // method is called } } class Synch { /* this line contains a keyword class that shows that a class is going to start and Synch is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ // Your program begin with a call to main. public static void main(String args[]) { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); // class’ objects are initialized n declared
  • 30. 30 // wait for threads to end try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ ob1.t.join(); ob2.t.join(); ob3.t.join(); // here join() method is called that waits for a thread to finish } catch(InterruptedException e) { System.out.println("Interrupted"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ }// closing curly brace } is used to close the definition of catch() block } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class Output:
  • 31. 31 Discussion: This program shows that how the output will look like without synchronization. A class Callme is created first. Then strings are declared and displayed. In class Caller that implements Runnable a new thread is starts then call() method is called in run method that calls the String throught msg. Then try catch block try to synchronize the string as shown in output also using join() method. Program 81: write a code that uses synchronized block Solution: // This program uses a synchronized block. class Callme { /* this line contains a keyword class that shows that a class is going to start and Callme is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ void call(String msg) { System.out.print("[" + msg); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ Thread.sleep(1000); // thread will sleep/paused for the time given in parenthesis } catch (InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println("Interrupted");
  • 32. 32 /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. If any exception occurs then this line of code will display Interrupted */ } System.out.println("]"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis.*/ } } class Caller implements Runnable { String msg; // a string msg is declared Callme target; // class’s object Thread t; // t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s constructor, a new Thread object is created public Caller(Callme targ, String s) { // 2 argument constructor target = targ; msg = s; t = new Thread(this); // t is initializes t.start(); // t starts } // synchronize calls to call() public void run() { synchronized(target) { // synchronized block
  • 33. 33 target.call(msg); // call() is called } } } class Synch1 { /* this line contains a keyword class that shows that a class is going to start and Synch1 is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ public static void main(String args[]) { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); // class’ instances are declared and initializes // wait for threads to end try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ ob1.t.join(); ob2.t.join(); ob3.t.join();
  • 34. 34 // here join() method is called that waits for a thread to finish } catch(InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println("Interrupted"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis if any exception occurs.*/ } // end of catch block } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class Output: Discussion: This program shows that how the output will look like if it is synchronized. A class Callme is created first. Then another class Synch1 is created that contains the main method. Then a call method is declared having msg string as a parameter and then displays it too. Then try catch block is declared that displays the strings. In class Caller that implements Runnable a new thread is starts then caller() method is declared having 2 arguments and it starts the thread using its object. Then synchronize calls to Call() method is which synchronized block is declared then in the main method creating 3 objects of Callme class are declared and initialized . Synchronized statement is used inside the caller’s run() method and shows the synchronized output.
  • 35. 35 Program 82: write an incorrect implementation of a producer and consumer Solution: // An incorrect implementation of a producer and consumer. class Q { /* this line contains a keyword class that shows that a class is going to start and Q is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ int n; // local variable of type int synchronized int get() { // When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time so for this synchronized get() method is used System.out.println("Got: " + n); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ return n; // it will return n } synchronized void put(int n) { // When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time so for this synchronized put() method is used this.n = n; // reference of object n is stored System.out.println("Put: " + n); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ }
  • 36. 36 } class Producer implements Runnable { /* this line contains a keyword class that shows that a class is going to start and Producer is the name of this class and it implements Runnable an abstract class. Opening curly brace { shows that form here a class’ definition is going to begin */ Q q; // instance of class Q Producer(Q q) { // Constructor of Producer class. this.q = q; // stores reference of q new Thread(this, "Producer").start(); // new Thread starts } public void run() { /* public is a keyword which means that this method is publically accessible, void means that it has no return type, run() is the abstract method of abstract class Runnable and it is implemented here, Opening Curly Brace { means that the method’s def. is going to start. */ int i = 0; /// a variable i of type int while(true) { q.put(i++); // if condition is true then i will increment } } } class Consumer implements Runnable { /* this line contains a keyword class that shows that a class is going to start and Consumer is the name of this class & it implements Runnable an abstract class. Opening curly brace { shows that form here a class’ definition is going to begin */ Q q; // instance of class Q Consumer(Q q) {
  • 37. 37 // Constructor of Consumer class. this.q = q; // reference of q is stored new Thread(this, "Consumer").start(); // new thread starts here } public void run() { /* public is a keyword which means that this method is publically accessible, void means that it has no return type, run() is the abstract method of abstract class Runnable and it is implemented here, Opening Curly Brace { means that the method’s def. is going to start. */ while(true) { q.get(); // if true then get() function works } } } class PC { /* this line contains a keyword class that shows that a class is going to start and PC is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ // Your program begin with a call to main. public static void main(String args[]) { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop.");
  • 38. 38 /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class Output: Discussion: In this program put(), get() and run methods are used. Consumer the threaded object that is consuming queues entries is also used. In Q put and get methods are synchronized, nothing stops the producer from overrunning the consumer, nor will anything stop the consumer from consuming the same queue value twice. Thus, we get the erroneous output shown above. Program 83: write a correct implementation of a producer and consumer. Solution: // A correct implementation of a producer and consumer. class Q { /* this line contains a keyword class that shows that a class is going to start and Q is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ int n; // local variable is initialized boolean valueSet = false;
  • 39. 39 // a variable of type Boolean is initialized and declared synchronized int get() { // When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time so for this synchronized get() method is used while(!valueSet) try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ wait(); // wait() tells the calling object to gine up the monitor and go to sleep until some other threads enter the same monitor and calls the notify. } catch(InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println("InterruptedException caught"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis if any exception occurs. */ } System.out.println("Got: " + n); //This line of code will display the String written inside the parenthesis. valueSet = false; notify(); // notify() method wakes up the first thread that called wait() on the same object return n; // returns n } synchronized void put(int n) {
  • 40. 40 while(valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); //If any exception occurs then this line of code will display that InterruptedException caught. } this.n = n; valueSet = true; System.out.println("Put: " + n); // This line of code will display the String written inside the parenthesis. notify(); } } class Producer implements Runnable { /* this line contains a keyword class that shows that a class is going to start and Producer is the name of this class & it implements Runnable an abstract class. Opening curly brace { shows that form here a class’ definition is going to begin */ Q q; Producer(Q q) { this.q = q; // stores reference of q new Thread(this, "Producer").start(); // new thread starts } public void run() {
  • 41. 41 /* public is a keyword which means that this method is publically accessible, void means that it has no return type, run() is the abstract method of abstract class Runnable and it is implemented here, Opening Curly Brace { means that the method’s def. is going to start. */ int i = 0; // local variable of type int while(true) { q.put(i++); // if true the condition is then i will increases } } } class Consumer implements Runnable { /* this line contains a keyword class that shows that a class is going to start and Consumer is the name of this class & it implements Runnable an abstract class. Opening curly brace { shows that form here a class’ definition is going to begin */ Q q; Consumer(Q q) { this.q = q; // stores reference of q new Thread(this, "Consumer").start(); // new thread starts here } public void run() { while(true) { q.get(); } } } class PCFixed {
  • 42. 42 /* this line contains a keyword class that shows that a class is going to start and PCFixed is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ public static void main(String args[]) { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class Output:
  • 43. 43 Discussion: In this program inside get() method another method wait() is called. This causes its execution to suspend until the Producer Tell us that some data is ready is execute. When this happens, execution inside get() starts. After the data has been obtained, get() calls notify() method. Using put() method more data will be added and then again the wait() method is called, which stops the execution until the data is removed from queue. When execution resumes, the next item of data is put in the queue, and notify() method is called. This tells the Consumer that it should now remove it. Program 84: write an example of deadlock Solution: // An example of deadlock. class A { /* this line contains a keyword class that shows that a class is going to start and A is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ synchronized void foo(B b) { // When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time so for this synchronized put() method is used String name = Thread.currentThread().getName(); // get the name of current thread System.out.println(name + " entered A.foo"); // This line of code will display the String written inside the parenthesis. try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ Thread.sleep(1000); // thread sleeps/pauses for given interval of time } catch(Exception e) {
  • 44. 44 System.out.println("A Interrupted"); // If any exception occurs then this line of code will display the String written inside the parenthesis. } System.out.println(name + " trying to call B.last()"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ b.last(); // last method is called } synchronized void last() { // When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time so for this synchronized get() method is used System.out.println("Inside A.last"); // This line of code will display the String written inside the parenthesis. } } class B { synchronized void bar(A a) { String name = Thread.currentThread().getName(); System.out.println(name + " entered B.bar"); // This line of code will display the String written inside the parenthesis. try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ Thread.sleep(1000);
  • 45. 45 } catch(Exception e) { System.out.println("B Interrupted"); // If any exception occurs then this line of code will displays the String written inside the parenthesis. } // end of catch block System.out.println(name + " trying to call A.last()"); // This line of code will display the String written inside the parenthesis. a.last(); } synchronized void last() { System.out.println("Inside A.last"); // This line of code will display the String written inside the parenthesis. } } class Deadlock implements Runnable { /* this line contains a keyword class that shows that a class is going to start and Deadlock is the name of this class & it implements Runnable an abstract class. Opening curly brace { shows that form here a class’ definition is going to begin */ A a = new A(); // an object of class A in initialized and declared B b = new B(); // an object of class B in initialized and declared Deadlock() { // constructor of the class Thread.currentThread().setName("MainThread"); // set the name of default constructor Thread t = new Thread(this, "RacingThread"); // new thread is initialized t.start();
  • 46. 46 a.foo(b); // get lock on a in this thread. System.out.println("Back in main thread"); // This line of code will display the String written inside the parenthesis. } public void run() { b.bar(a); // get lock on b in other thread. System.out.println("Back in other thread"); // This line of code will display the String written inside the parenthesis. } // Your program begin with a call to main. public static void main(String args[]) { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ new Deadlock(); } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class
  • 47. 47 Output: Discussion: In this program deadlock is used which is a special type of error that needs to be avoid. It relates specifically to multitasking which occurs when two threads have a circular dependency on a pair of synchronized objects. As the program has deadlocked, we have to press CTRL-C to end the program. The RacingThread owns the monitor on b, while it is waiting for the monitor on a. At the same time, MainThread owns a and is waiting to get b. This program will never complete. Program 85: write a code that demonstrates the use of suspend() and resume(). Solution: // Using suspend() and resume(). class NewThread implements Runnable { /* this line contains a keyword class that shows that a class is going to start and NewThread is the name of this class & it implements Runnable. Opening curly brace { shows that form here a class’ definition is going to begin */ String name; // name of thread. A variable of type String known as name Thread t; // a thread t is declared NewThread(String threadname) { // an argument constructor is created
  • 48. 48 name = threadname; t = new Thread(this, name); // thread is initialized and stores reference of name System.out.println("New thread: " + t); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will print the new thread that is stored in the object of thread i.e t */ t.start(); // Start the thread } // This is the entry point for thread. public void run() { try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ for(int i = 15; i > 0; i--) { /*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will check the condition that either it is true or not, if it is true then the next statement will be compiled, after that control/system will pass to the iteration process then it will check the condition if it is fulfilled then the statement given below will be executed again i.e it will go on increasing the value of i by 1 until the condition is not satisfied*/ System.out.println(name + ": " + i); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line of code will display the String written inside the parenthesis. */ Thread.sleep(200); }
  • 49. 49 } catch (InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println(name + " interrupted."); // If any exception occurs then this line of code will display the string written inside parenthesis. } System.out.println(name + " exiting."); // This line of code will display the String written inside the parenthesis. } } class SuspendResume { /* this line contains a keyword class that shows that a class is going to start and SuspendResume is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ // Your program begin with a call to main. public static void main(String args[]) { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); // 2 new objects of class are initialized and declared try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/
  • 50. 50 Thread.sleep(1000); ob1.t.suspend(); // obj1 is suspended System.out.println("Suspending thread One"); // This line of code will display the String written inside the parenthesis. Thread.sleep(1000); ob1.t.resume(); //// obj1 is resumed System.out.println("Resuming thread One"); // This line of code will display the String written inside the parenthesis. ob2.t.suspend(); // obj2 is suspended System.out.println("Suspending thread Two"); // This line of code will display the String written inside the parenthesis. Thread.sleep(1000); // thread sleeps for the given interval of time ob2.t.resume(); //// obj1 is resumes System.out.println("Resuming thread Two"); // This line of code will display the String written inside the parenthesis. } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); // If any exception occurs then this line of code will display that Main thread interrupted. } // wait for threads to finish try { /* From this line of code the try block starts. Opening delimiter shows that try block’s definition is going to start. This block will try to interpret what is written inside it. Otherwise exception will occur that will be caught by the catch block, written right after the try block*/ System.out.println("Waiting for threads to finish.");
  • 51. 51 // This line of code will display the String written inside the parenthesis. ob1.t.join(); ob2.t.join(); // here join() method is called that waits for a thread to finish } catch (InterruptedException e) { // catch block catches exception if it occurs and stored it in its object e System.out.println("Main thread Interrupted"); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. If any exception occurs then this line of code will display that Main thread interrupted */ } // closing curly brace } is used to close the definition of catch block System.out.println("Main thread exiting."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. It will print the String written inside it in double quotes*/ } }
  • 52. 52 Output: Discussion: The demo contains suspend() and resume() methods. These methods are defined by Thread to pause and restart the execution of thread. This program creates 2 objects ob1 and ob2 and displays each’ thread with an interval or pause by suspend() and sleep() methods. It also resumes the working of both the
  • 53. 53 objects and then displays that both the threads are exiting including main thread. The thread class also defines a method called stop() that stops a thread. Once a thread has been stopped, it cannot be restarted using resume() method. Program 86: Write a program that uses buffer reader to read the characters. Solution: // Use a BufferedReader to read characters from the console. import java.io.*; /* first of all import a java.io package which is knows as basic input output package. It is a package that handles byte streams like input stream, output stream etc*/ class BRRead { /* this line contains a keyword class that shows that a class is going to start and BRRead is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ public static void main(String args[]) /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ throws IOException{ char c; // character c is declared BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); /* use to create a character stream Br is a character based stream that is linked to the console through system.in and buffer reader supports a buffer input stream. System.in is a line buffered by default*/ System.out.println("Enter characters, 'q' to quit.");
  • 54. 54 /* read characters. System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line */ Do { // loop starts c = (char) br.read(); // characters will be read from the console and stored in c System.out.println(c); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. // This line of code will display the String written inside the parenthesis. */ } while(c != 'q'); // it will give output until we press q ( loop ends) } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class
  • 55. 55 Output: Discussion: This demo first wants the user to type a string then reads a character from the console using BufferedReader and read() methods. Each time that read() method is called, it reads a character from the input stream and returns it one by one. It returns –1 when the end of the stream is encountered. No input is passed to the program until we press enter. This program continues it’s working until user type q to quit. Program 87: write a program that reads the string from console. Solution: // Read a string from console using a BufferedReader. import java.io.*; /* first of all import a java.io package which is knows as basic input output package. It is a package that handles byte streams like input stream, output stream etc*/ class BRReadLines {
  • 56. 56 /* this line contains a keyword class that shows that a class is going to start and BRReadLines is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ public static void main(String args[]) throws IOException{ /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin and throwsIOException means that this code can throw exception*/ // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); /* use to create a character stream Br is a character based stream that is linked to the console through system.in and buffer reader supports a buffer input stream. System.in is a line buffered by default*/ String str; // a variable str of type string is declared System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. // These lines of code will display the String written inside the parenthesis. */ do { // loop starts str = br.readLine(); /* br is the instance of BufferReader that by using dot operator calls a readLine() method and stores it in the variable str of type string */ System.out.println(str); // This line of code will display the String written inside the parenthesis. } while(!str.equals("stop"));
  • 57. 57 // when the entered string will be equal to stop then the program quit } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class Output: Discussion: In this demo BufferedReader()and inputSteamReader() methods are used that first wants the user to type a string then they read it and dislay is again. To read a string from the console readLine() method is used that is a member of the BufferedReader class. The process continues until the user type stop. Program 88: Write a program that reads upto 100 lines or until you enter stop. It uses buffer reader to read from the console. Solution: // A tiny editor. import java.io.*;
  • 58. 58 /* first of all import a java.io package which is knows as basic input output package. It is a package that handles byte streams like input stream, output stream etc*/ class TinyEdit { /* this line contains a keyword class that shows that a class is going to start and TinyEdit is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ public static void main(String args[]) throws IOException { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin and throwsIOException means that this code can throw exception */ // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); /* use to create a character stream Br is a character based stream that is linked to the console through system.in and buffer reader supports a buffer input stream. System.in is a line buffered by default*/ String str[] = new String[100]; // a string str of size 100 is declared and initialized here. System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); /* System is a built in function used to give access to the system. Out is used for the output. Println is used to print or display the string passed to it & ln is used to goto the next line. Semicolon is used to terminate the statement/line. These line of code will display the String written inside the parenthesis. */ for(int i=0; i<100; i++) { /*a for loop is declared here it contains three parts initialization that initializes n to 0, condition i.e n is less than 100, iteration i.e increment of n. Firstly loop initialize n to 0 and then it will check the condition that either it is true or not, if it is true then the next statement will be
  • 59. 59 compiled, after that control/system will pass to the iteration process then it will check the condition if it is fulfilled then the statement given below will be executed again i.e it will go on increasing the value of n by 1 until the condition is not satisfied*/ str[i] = br.readLine(); /* br is the instance of BufferReader that by using dot operator calls a readLine() method and stores it in the variable str[i] of type string */ if(str[i].equals("stop")) break; // if the given condition is satisfied then it will break } System.out.println("nHere is your file:"); // This line of code will display the String written inside the parenthesis. for(int i=0; i<100; i++) { /*a for loop is declared here it contains three parts initialization that initializes n to 0, condition i.e n is less than 100, iteration i.e increment of n. Firstly loop initialize n to 0 and then it will check the condition that either it is true or not, if it is true then the next statement will be compiled, after that control/system will pass to the iteration process then it will check the condition if it is fulfilled then the statement given below will be executed again i.e it will go on increasing the value of n by 1 until the condition is not satisfied*/ if(str[i].equals("stop")) break; // if the given condition is satisfied then it will break System.out.println(str[i]); // This line of code will display the String written inside the parenthesis. } }// closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class
  • 60. 60 Output: Discussion: In this demo using BufferedReader() and fileInputStreamReader() the data written on the console will be displayed again on it. BufferedReader() method reads the text from the console. This demo first wants us to write the lines of the text then if we want to stop then wants us to type stop just in the same way as it is mentione on console then the compiler compares it to the string already declared to “stop” if it matches then it will display what you entered/ type. It will read up to 100 lines or until we enter stop. Program 89: write a program that uses Print Writer to handle the console. Solution: // Demonstrate PrintWriter import java.io.*; /* first of all import a java.io package which is knows as basic input output package. It is a package that handles byte streams like input stream, output stream etc*/ public class PrintWriterDemo {
  • 61. 61 /* this line contains a keyword class that shows that a class is going to start and PrintWriterDemo is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */ public static void main(String args[]) { /*this line of code shows that public is an access specifier that allows a programmer to control its visibility or access, means this class is accessible out of the class in which it is declared i.e anyone publically can access it. Static is a keyword that allows the main() method to be execute without instantiating an instance of that class. Void means this main() method has no return type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly brace { shows that form here the method’s definition is going to begin */ PrintWriter pw = new PrintWriter(System.out, true); // printWriter is used to write to the console. system.out is used for the output stream and flush the stream after each new line pw.println("This is a string"); // display this text int i = -7; // a local variable i of type int pw.println(i); // displays i on the command prompt double d = 4.5e-7; // a local variable d of type double pw.println(d); // displays d on the console } // closing curly brace } is used to close the definition of main() method } // closing curly brace } is used to close the definition of class Output: