Multithreading 12
Multithreading 12
(OOP)
2
Introduction
• In single-processor systems, the multiple
threads share CPU time, known as time
sharing (OS)
• Multithreading can make your program more
responsive & interactive, as well as enhance
performance
• For example, a good word processor lets you
print or save a file while you are typing
3
Multi-threading in Java
• Java provides good support for creating and
running threads & for locking resources to
prevent conflicts
• In Java, each task is an instance of the
Runnable interface, also called a runnable
object
• Tasks are objects. To create tasks, you have
to first define a class for tasks, which
implements the Runnable interface
• The Runnable interface is very simple and
contains the run method
4
Multi-threading in Java
5
An Example
public class TaskThreadDemo { times = t;
public static void main(String[] args) { }
// Create tasks @Override /** Override the run() method to tell
Runnable printA = new PrintChar('a', 100); the system
Runnable printB = new PrintChar('b', 100); * what task to perform */
Runnable print100 = new PrintNum(100); public void run() {
// Create threads for (int i = 0; i < times; i++) {
Thread thread1 = new Thread(printA); System.out.print(charToPrint);
Thread thread2 = new Thread(printB); }
Thread thread3 = new Thread(print100); }
// Start threads }
thread1.start(); // The task class for printing numbers from 1 to
thread2.start(); n for a given n
thread3.start(); class PrintNum implements Runnable {
} private int lastNum;
} /** Construct a task for printing 1, 2, ..., n
// The task for printing a character a specified */
number of times public PrintNum(int n) {
class PrintChar implements Runnable { lastNum = n;
private char charToPrint; // The character to print}
private int times; // The number of times to repeat
@Override /** Tell the thread how to run */
/** Construct a task with a specified character and number
public of run() {
void
* times to print the character */ for (int i = 1; i <= lastNum; i++) {
public PrintChar(char c, int t) { System.out.print(" " + i);
charToPrint = c; }
}
} 6
Event Classes