ZeePedia

JAVA: Multithreading 2

<< JAVA: Multithreading 1
JAVA Web Application Development >>
img
Web Design & Development ­ CS506
VU
Lesson 24
More on Multithreading
In this handout, we'll cover different aspects of multithreading. Some examples are given to make you
understand the topic of multithreading. First we will start with an example that reads data from two text
files simultaneously.
Example Code: Reading Two Files Simultaneously
The task is to read data from file "first.txt" & "second.txt" simultaneously. Suppose that files contains the
following data as shown below
first.txt
second.txt
Following is the code for ReadFile.java that implements Runable interface. The file reading code will be
written inside the run( ) method.
// File ReadFile.java
import java.io.*;
public class ReadFile implements Runnable{
//attribute used for name of file
String fileName;
// param constructor
public ReadFile(String fn){
fileName = fn;
}
// overriding run method// this method contains the code for file reading
public void run ( ){
try
{ // connecting FileReader with attribute fileNameFileReader fr = new
FileReader(fileName);BufferedReader br = new BufferedReader(fr);
String line = "";
// reading line by line data from file// and displaying it on console
line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
fr.close();
br.close();
}catch (Exception e){
System.out.println(e);
}
} // end run() method
} // File Test.java
public class Test {
public static void main (String args[]){
// creating ReadFile objects by passing file names to them
ReadFile first = new ReadFile("first.txt");
ReadFile second = new ReadFile("second.txt");
175
img
Web Design & Development ­ CS506
VU
// Instantiating thread objects and passing
// runnable (ReadFile) objects to them
Thread t1 = new Thread(first);
Thread t2 = new Thread(second);
// starting threads that cause threads to read data from
// two different files simultaneously
t1.start();
t2.start();
}
}
Output
On executing Test class, following kind output would be generated:
Now let's discuss some useful thread class methods.
. sleep(int time) method
-Causes the currently executing thread to wait for the time (milliseconds) specified
-Waiting is efficient equivalent to non-busy. The waiting thread will not occupy the processor
-Threads come out of the sleep when the specified time interval expires or when interrupted by some
other thread
-Thread coming out of sleep may go to the running or ready state depending upon the availability of the
processor. The different states of threads will be discussed later
-High priority threads should execute sleep method after some time to give low priority threads a
chance to run otherwise starvation may occur
-sleep() method can be used for delay purpose i.e. anyone cal call Thread.sleep()method
-Note that sleep() method can throw InterruptedException. So, you need try-catch block
Example Code: Demonstrating sleep ( ) usage
Below the modified code of Worker.java is given that we used in the previous handout.
// File Worker.javapublic class Worker implements Runnable {
private String job ;
//Constructor of Worker class
public Worker (String j ){
176
img
Web Design & Development ­ CS506
VU
job = j;
}
//Implement run() method of Runnable interface
public void run ( ) {
for(int i=1; i<= 10; i++) {
try { Thread.sleep(100); // go to sleep for 100 ms}catch
(Exception ex){System.out.println(ex);}
System.out.println(job + " = " + i);} // end for} // end
run } // end class
// File SleepEx.java
public class SleepEx {
public static void main (String args[ ]){
// Creating Worker objects
Worker first = new Worker ("first job");
Worker second = new Worker ("second job");
// Instantiating thread class objects
Thread t1 = new Thread (first );
Thread t2 = new Thread (second);
// starting thread
t1.start();
t2.start();
}
} // end class
Output
On executing SleepEx.java, the output will be produced with exact alternations between first thread &
second thread. On starting threads, first thread will go to sleep for 100 ms. It gives a chance to second
thread to execute. Later this thread will also go to sleep for 100 ms. In the mean time the first thread will
come out of sleep and got a chance on processor. It will print job on console and again enters into sleep
state and this cycle goes on until both threads finished the run() method
Before jumping on to example code, lets reveal another aspect about main() method. When you run a Java
program, the VM creates a new thread and then sends the main(String[] args) message to the class to be
run! Therefore, there is always at least one running thread in existence. However, we can create more
177
img
Web Design & Development ­ CS506
VU
threads which can run concurrently with the existing default thread.
sleep() method can be used for delay purpose. This is demonstrated in the DelayEx.java given below
// File DelayEx.java public class DelayEx { public static void
main (String args[ ]){ System.out.println("main thread going
to sleep");
try {
// the main thread will go to sleep causing delay
Thread.sleep(100);
}catch (Exception ex){
System.out.println(ex);
}
System.out.println("main thread coming out of sleep"); } // end main() }
// end class
Output
On executing DelayEx class, you will experience a delay after the first statement displayed. The second
statement will print when the time interval expired. This has been show below in the following two
diagrams:
. yield( ) method
-Allows any other threads of the same priority to execute (moves itself to the end of the priority queue)
-If all waiting threads have a lower priority, then the yielding thread resumes execution on the
CPU
-Generally used in cooperative scheduling schemes
Example Code: Demonstrating yield ( ) usage
Below the modified code of Worker.javais given
// File Worker.javapublic class Worker implements
Runnable { private String job ;
//Constructor of Worker class
public Worker (String j ){
job = j;
}
//Implement run() method of Runnable interface
public void run ( ) {
for(int i=1; i<= 10; i++) {
// giving chance to a thread to execute of same priority
178
img
Web Design & Development ­ CS506
VU
Thread.yield( );
System.out.println(job + " = " + i);
} // end for
} // end run
} // end class // File YieldEx.java
public class YieldEx {
public static void main (String args[ ]){
// Creating Worker objects
Worker first = new Worker ("first job");
Worker second = new Worker ("second job");
// Instantiating thread class objects
Thread t1 = new Thread (first );
Thread t2 = new Thread (second);
// starting thread
t1.start();
t2.start();
}
} // end class
Output
Since both threads have the same priority (until we change the priority of some thread explicitly). Therefore
both threads will execute on alternate basis. This can be confirmed from the output given below:
A thread can be in different states during its lifecycle as shown in the figure.
179
img
Web Design & Development ­ CS506
VU
180
img
Web Design & Development ­ CS506
VU
Thread t2 = new Thread (second);
System.out.println("Starting...");
// starting threads
t1.start();
t2.start();
// The current running thread (main) blocks until both //workers have finished
try {
t1.join();
t2.join();
}catch (Exception ex) {System.out.println(ex);}
System.out.println("All done ");
} // end main}
Output
On executing JoinEx, notice that "Starting" is printed first followed by printing workers jobs. Since main
thread do not finish until both threads have finished their run( ). Therefore "All done" will be print on last.
References:
Java, A Practical Guide by Umair Javed
Java tutorial by Sun: http://java.sun.com/docs/books/tutorial/
CS193j handouts on Stanford
181