Module 4 - Threads in Java
Module 4 - Threads in Java
video networking
interaction
Advantages
• easier to program
– 1 thread per task
• can provide better performance
– thread only runs when needed
– no polling to decide what to do
• multiple threads can share resources
• utilize multiple processors if available
Disadvantage
• multiple threads can lead to deadlock
– much more on this later
• overhead of switching between threads
Creating Threads (method 1)
• extending the Thread class
– must implement the run() method
– thread ends when run() method finishes
– call .start() to get the thread ready to run
Creating Threads Example 1
class Output extends Thread {
private String toSay;
public Output(String st) {
toSay = st;
}
public void run() {
try {
for(;;) {
System.out.println(toSay);
sleep(1000);
}
} catch(InterruptedException e) {
System.out.println(e);
}
}
}
Example 1 (continued)
class Program {
public static void main(String [] args) {
Output thr1 = new Output(“Hello”);
Output thr2 = new Output(“There”);
thr1.start();
thr2.start();
}
}
stop(),
start() end of run method
runnable
new dead
wait(), notify(),
I/O request, I/O completion,
suspend() resume()
blocked
Java Thread Example 1
class Job implements Runnable {
private static Thread [] jobs = new Thread[4];
private int threadID;
public Job(int ID) {
threadID = ID;
}
public void run() { do something }
public static void main(String [] args) {
for(int i=0; i<jobs.length; i++) {
jobs[i] = new Thread(new Job(i));
jobs[i].start();
}
try {
for(int i=0; i<jobs.length; i++) {
jobs[i].join();
}
} catch(InterruptedException e) { System.out.println(e); }
}
}
Java Thread Example 2
class Schedule implements Runnable {
private static Thread [] jobs = new Thread[4];
private int threadID;
public Schedule(int ID) {
threadID = ID;
}
public void run() { do something }
public static void main(String [] args) {
int nextThread = 0;
setPriority(Thread.MAX_PRIORITY);
for(int i=0; i<jobs.length; i++) {
jobs[i] = new Thread(new Job(i));
jobs[i].setPriority(Thread.MIN_PRIORITY);
jobs[i].start();
}
try {
for(;;) {
jobs[nextThread].setPriority(Thread.NORM_PRIORITY);
Thread.sleep(1000);
jobs[nextThread].setPriority(Thread.MIN_PRIORITY);
nextThread = (nextThread + 1) % jobs.length;
}
} catch(InterruptedException e) { System.out.println(e); }
}
}