Multithreading in Java: Nelson Padua-Perez Bill Pugh
Multithreading in Java: Nelson Padua-Perez Bill Pugh
Nelson Padua-Perez
Bill Pugh
Two tasks
Multiprocessing (Multithreading)
Approach
Multiple processing units (multiprocessor)
Computer works on several tasks in parallel
Performance can be improved
new start
IO complete,
new runnable
sleep expired,
join complete,
terminate acquire lock
blocked
IO, sleep, join,
request lock
terminated
Threads – Scheduling
Scheduler
Determines which runnable threads to run
Can be based on thread priority
Part of OS or Java Virtual Machine (JVM)
Many computers can run multiple threads
simultaneously (or nearly so)
Java Thread Example
public class ThreadExample implements Runnable {
public void run() {
for (int i = 0; i < 3; i++)
System.out.println(i);
}
public static void main(String[] args) {
new Thread(new ThreadExample()).start();
new Thread( new ThreadExample()).start();
System.out.println("Done");
}
}
Java Thread Example – Output
Possible outputs
0,1,2,0,1,2,Done // thread 1, thread 2, main()
0,1,2,Done,0,1,2 // thread 1, main(), thread 2
Done,0,1,2,0,1,2 // main(), thread 1, thread 2
0,0,1,1,2,Done,2 // main() & threads interleaved
Synchronization
can be used to control thread execution order
Using Synchronization
public class DataRace implements Runnable {
static volatile int x;
static Object lock = new Object();
public void run() {
for (int i = 0; i < 10000; i++)
synchronized(lock) {
x++; x--;
}
}
public static void main(String[] args) throws Exception {
Thread [] threads = new Thread[100];
for (int i = 0; i < threads.length; i++)
threads[i] = new Thread(new DataRace());
for (int i = 0; i < threads.length; i++)
threads[i].start();
for (int i = 0; i < threads.length; i++)
threads[i].join();
System.out.println(x); // x always 0!
}
}