A thread is a fl ow of control through a program.
Unlike a process, a thread does not have a separate allocation of memory, but shares memory with other threads created by the same application.
Threads created by an application can share global variables.
We cannot avoid using threads in Java, since each program will have at least one thread that is launched automatically by our machine’s JVM when that program is executed.
Which thread is given to the processor depends on
• Thread priority (1–10, in increasing order of importance) in Java.
• Whether scheduling is pre-emptive or cooperative.
A pre-emptive scheduler will determine when a thread has had its fair share of CPU time (possibly via simple time allocation) and will then pause it (temporarily).
A cooperative scheduler, on the other hand, will wait for the running thread to pause itself before giving control of the CPU to another thread. A JVM using cooperative scheduling is thus much more susceptible to thread starvation.
On PCs, threads with the same priority are each given an equal time-slice or time quantum for execution on the processor.
When the quantum expires, the first thread is suspended and the next thread in the queue is given the processor, and so on. If some threads require more urgent attention than others, then they may be assigned
higher priorities (allowing pre-emption to occur).
Using Threads in Java
The run method specifies the actions that a thread is to execute and serves the same purpose for the process running on the thread as method main does for a full application program.
Like main , run may not be called directly. The containing program calls the start method (inherited from class Thread ), which then automatically calls run.
In practice, of course, different threads will normally carry out different tasks.
If we want the threads to carry out actions different from each other’s, then we must create a separate class for each thread (each with its own run method)
Multithreaded Servers
There are two possible solutions:
- use a non-blocking server
- use a multithreaded server
Multithreaded server
The basic technique involves a two-stage process:
1. the main thread (the one running automatically in method main ) allocates individual threads to incoming clients;
2. the thread allocated to each individual client then handles all subsequent interaction between that client and the server (via the thread’s run method).
import java.io.*;
import java.net.*;
public class MultiEchoServer {
private static ServerSocket serverSocket;
private static final int PORT = 1234;
public static void main(String[] args) throws IOException {
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException ioEx) {
System.out.println("\nUnable to set up port!");
System.exit(1);
}
do {
// Wait for client…
Socket client = serverSocket.accept();
System.out.println("\nNew client accepted.\n");
// Create a thread to handle communication with
// this client and pass the constructor for this
// thread a reference to the relevant socket…
ClientHandler handler = new ClientHandler(client);
handler.start();// As usual, method calls run .
} while (true);
}
}
class ClientHandler extends Thread {
private Socket client;
private Scanner input;
private PrintWriter output;
public ClientHandler(Socket socket) {
// Set up reference to associated socket…
client = socket;
try {
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
public void run() {
String received;
do {
// Accept message from client on
// the socket's input stream…
received = input.nextLine();
// Echo message back to client on
// the socket's output stream…
output.println("ECHO: " + received);
// Repeat above until 'QUIT' sent by client…
} while (!received.equals("QUIT"));
try {
if (client != null) {
System.out.println("Closing down connection…");
client.close();
}
} catch (IOException ioEx) {
System.out.println("Unable to disconnect!");
}
}
}
Locks and Deadlock
Data Integrity requires locking and the side effect of locking is deadlock
Any other (updating) thread must wait until the lock has been released. Once the fi rst thread has fi nished its updating, it should release the lock, making it available to other such threads.
Threads requiring read-only access do not need to obtain a lock.