Академический Документы
Профессиональный Документы
Культура Документы
An Introduction to
Multi-threading
12
MARCH 2008
www.openITis.com
cmyk
Overview
created in main).
Asynchronous execution
Note that created threads run asynchronously. This
means that threads do not run sequentially (like function
calls); rather, the order of execution of threads is not
predictable. To understand this, let us extend our simple
program here:
class MyThread extends Thread {
public void loop() {
for(int i = 0; i < 3; i++) {
System.out.println(In thread +
Thread.currentThread().getName() +
; iteration + i);
try {
Thread.sleep((int)Math.random());
}
catch(InterruptedException ie) {
ie.printStackTrace();
}
}
The basics
A Java thread can be created in two ways: by
implementing the Runnable interface or by extending
the Thread class. Both have a method called run. This
method will be called by the runtime when a thread
starts executing.
A thread can be created by invoking the start method
on a Thread or its derived objects. This in turn calls the
run method and keeps the thread in running state. Now
let us look at a simple example using threads.
}
public void run() {
System.out.println(This is new thread);
this.loop();
}
public static void main(String args[]) throws Exception {
MyThread mt = new MyThread();
mt.start();
System.out.println(This is the main Thread);
mt.loop();
mt.start();
www.openITis.com
cmyk
MARCH 2008
13
Overview
Thread synchronisation
10 milli-seconds.
The main thread (main) and the child thread
(hread-0) are executed independently. The output
is not fixed and the order of executing the iterations
in the threads is not predictable. This is one of the
fundamental and important concepts to understand in
multi-threading.
Data races
Threads share memory and they can concurrently
modify data. This can lead to unintuitive results and end
in data races. Here is an example of a data race:
class Counter {
public static long count = 0;
Counter.count++;
System.out.print(Counter.count +
);
}
}
}
public class DataRace {
public static void main(String args[]) {
synchronized(this) {
t3.start();
}
}
14
);
t2.start();
Counter.count++;
System.out.print(Counter.count +
t1.start();
MARCH 2008
Deadlocks
Obtaining and using locks is tricky and can lead to lots
of problems, one of which (a common one) is known as
www.openITis.com
cmyk
Overview
t1.start();
t2.start();
}
}
class Balls {
public static long balls = 0;
}
class Runs {
public static long runs = 0;
}
class Counter implements Runnable {
public void IncrementBallAfterRun() {
synchronized(Runs.class) {
synchronized(Balls.class) {
Runs.runs++;
Balls.balls++;
}
}
}
public void IncrementRunAfterBall() {
synchronized(Balls.class) {
synchronized(Runs.class) {
Balls.balls++;
Runs.runs++;
}
}
}
public void run() {
IncrementBallAfterRun();
IncrementRunAfterBall();
}
}
www.openITis.com
cmyk
MARCH 2008
15