|
Network Programming ![]() This website demonstrates using wikis as teaching and learning tool. The course instructor is happy to share the teaching materials here with those who find it readable. |
Lecture /
Java Programming - MultithreadingA Network Programming Lecture by Steven Choy Lecture Overview: Introduction to Multithreading - Creating and Running Threads in Java - Thread Subclass - Runnable Implementation - Other Major Thread Concepts
Introduction
Examples
Single-threaded program flow
5 seconds reading file A
2 seconds processing file A
5 seconds reading file B
2 seconds processing file B
-----------------------
14 seconds total
Multi-threaded program flow
5 seconds reading file A
5 seconds reading file B + 2 seconds processing file A
2 seconds processing file B
-----------------------
12 seconds total
Benefits: Better resource utilization, Simpler program design
"If you were to program the above ordering of reading and processing by hand in a singlethreaded application, you would have to keep track of both the read and processing state of each file. Instead you can start two threads that each just reads and processes a single file. Each of these threads will be blocked while waiting for the disk to read its file. While waiting, other threads can use the CPU to process the parts of the file they have already read. The result is, that the disk is kept busy at all times, reading from various files into memory. This results in a better utilization of both the disk and the CPU. It is also easier to program, since each thread only has to keep track of a single file."
Benefit: More responsive programs
"Imagine a server application that listens on some port for incoming requests. when a request is received, it handles the request and then goes back to listening. The server loop is sketched below:"
while(server is active){
listen for request
process request
}
"If the request takes a long time to process, no new clients can send requests to the server for that duration. Only while the server is listening can requests be received."
"An alternate design would be for the listening thread to pass the request to a worker thread, and return to listening immediatedly. The worker thread will process the request and send a reply to the client. This design is sketched below:"
while(server is active){
listen for request
hand request to worker thread
}
"This way the server thread will be back at listening sooner. Thus more clients can send requests to the server. The server has become more responsive."
Creating and running threads
Method 1: Using a Thread Subclass
Step 1: Create a subclass of the Thread class, and override the run method to perform the task of the new thread.
public class MyThread extends Thread {
public void run(){
System.out.println("MyThread running");
}
}
Step 2: Create an instance of the subclass.
MyThread myThread = new MyThread(); Step 3: Invoke the start method on the subclass instance.
myTread.start(); Class Thread API Reference: http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html
Method 2: Implementing the Runnable Interface
Step 1: Create a class that implements the Runnable interface, and supply a run method to perform the task of the new thread.
public class MyRunnable implements Runnable {
public void run(){
System.out.println("MyRunnable running");
}
}
Step 2: Create an instance of the new class, and use it to create a Thread by the Thread(Runnable) or Thread(Runnable, String) constructor.
Thread thread = new Thread(new MyRunnable()); Step 3: Invoke the start method on the Thread object.
thread.start(); Interface Runnable API Reference: http://download.oracle.com/javase/6/docs/api/java/lang/Runnable.html
Examples
Some other thread concepts you need to know for advanced multithreading programming
Multiple threads running within a program may share the same resources. Therefore, there is a possibility that more than one thread can access the same object at the same time. Without taking appropriate care this could lead to what is known as a synchronization problem.
The life of a thread ends when its run method finishes execution. Sometimes, you may want to terminate a thread from another thread.
Class Exercises(Q1) What are the two ways of creating threads in Java?
(Q2) Is extending the Thread class in your Java programs always possible?
(Q3) For a multithreaded program, you will start a thread running by invoking the __________ method on your Thread object which will in turn invoke the _________ method.
(Q4) Compile and Run the first example. Write down the output of the program.
(Q5) Compile and Run the second example. Write down the output of the program.
(Q6) Study the first example. What will happen if the statement at line#21 is moved to between line#29 and line#30?
(Q7) Write a Java multithreading program to simulate a horse racing game.
The following code segment may be useful to you.
public void run() {
try {
for(int i = 100; i > 0; i--) {
System.out.println(horsename + "--> " + i);
Thread.sleep((long) (Math.random() * 100));
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Horse " + horsename + " finishes");
}
The following code template may be useful to you.
class Horse extends Thread { private String horsename; Horse(String name) { horsename = name; System.out.println("Horse " + horsename + " starts"); } // This is the entry point for the second thread. public void run() { // put code here for thread running code } } class HorseGame { public static void main(String args[]) { // put code to create and start threads } } ReadingThanks for ReadingIf you would rather like to have this lecture note in printed format, please click the print action link in the top right corner. If you find any problem in this lecture note, please feel free to tell Steven via steven@findaway.hk. |