Transcript Lab2

CSC 480
Software Engineering
Lab 2 – Multi-Threading
Oct 18, 2002
Thread – an analog

Program without multithreading is like
driving on a one-lane country road
 You

may stuck behind a large, wide hay-truck
With multithreading, different sequences of
activities can carry out concurrently
 Like
on a multi-lane highway, you can pass
truck and enjoy the scenery
Thread – the definition
A thread--sometimes called an execution
context or a lightweight process--is a
single sequential flow of control within a
program
 You use threads to isolate tasks

Java Thread Class


You extend Java’s Thread class to implement
threads
The run method gives a thread something to do
 This
method is the entry point for threads, just like the
main method for applications

A thread can be started by calling the start
method on the Thread object
method start the thread by calling the run
method
 This
Example – the knock-knock app

In the knock-knock application, a server that can
serve multiple clients needs the following class
public class KKMultiServerThread extends Thread {
private Socket socket = null;
public KKMultiServerThread(Socket socket) {
super("KKMultiServerThread");
this.socket = socket;
}
public void run() {
//…
}
}
Example – the KKMultiServer

In the KKMultiServer, a new
KKMultiServerThread is spawn when a
new client is identified
public class KKMultiServer {
public static void main(String[] args)
throws IOException {
boolean listening = true;
//…
while (listening)
new KKMultiServerThread(
serverSocket.accept()).start();
}
Synchronizing Threads
Each KKMultiServerThread threads
can be executed independently, since they
don’t share any common resources
 In the bank application, the execution of
bank service threads need to be
synchronized
 We’ll learn how to use object locks to
synchronize threads

The synchronized Keyword



The code segments within a program that
access the same object from separate,
concurrent threads are called critical sections.
In the Java language, a critical section can be a
block or a method and are identified with the
synchronized keyword.
The Java platform then associates a lock with
every object that has synchronized code.
Association – The Bank Server App
BankMultiServer
BankMulti
BankMultiService
BankAccount
doService()
processCommand()
Association – The Bank Client App
BankClientMultiMain
BankClientMultiFrame
BankClientConnector
request(String cmd):String