Sie sind auf Seite 1von 29

Java Threads and

Synchronization
Dr Matthew Grove
http://people.cs.vt.edu/~mjeg/

Slide credits: Dr B. Wilkinson & Raj Buyya


September 22, 2011

Thursday, September 22, 2011

Lecture Outline
Creating threads in Java.
Java synchronization.
Volatile variables.
Coordinating threads.
Concurrency in Java 5.
Java Concurrent Animated.

September 22, 2011

Thursday, September 22, 2011

Slide Credits
The following notes are based upon the Java tutorial at http://
java.sun.com/docs/books/tutorial/essential/concurrency/
Additional information from Raj Buyyas slides Multithreaded
Programming using Java Threads http://www.buyya.com

ITCS4145/5145, Parallel Programming B. Wilkinson Spring 2009.


Thursday, September 22, 2011

slides 8c-1

Effective Java

Joshua Bloch
ISBN-10: 0321356683
Chapter 9 Threads

September 22, 2011

Thursday, September 22, 2011

Thread class
Each thread is an object of the Thread class.
(Java tutorial says: Each thread is associated with an
instance of the class Thread.)
Java provide two basic ways to creates a thread:
1.Define a class that is derived class of the class Thread.
2.Make your class implement the Runnable interface

Thursday, September 22, 2011

Simplest way is:


1.Define a class that is derived class of the class Thread.

Object of this class is a thread.

Provide the method called run (which will override the


inherited run method, which does nothing).

The run method defines the code for the thread.

Invoke the start method which initiates the


computation of the thread

Thursday, September 22, 2011

Example
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
Java entry point

public static void main(String args[ ]) {


Create

HelloThread myThread = new HelloThread(); Thread


}

myThread.start(); Start thread and execute

object

run method

Thursday, September 22, 2011

Alternate way to create threads


2. Make your class implement the Runnable interface

The Thread class actually implements the interface called


Runnable.
The Runnable interface defines the single method, run, meant
to contain the code executed in the thread.

Thursday, September 22, 2011

Example
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[ ]) {
Thread tr = new Thread(new HelloRunnable());
tr.start();
}
}

Thursday, September 22, 2011

The Runnable object can subclass a class other than


Thread, i.e.:
public class MyRunnable extends SomeClass
implements Runnable {

}
Note: both the Thread class and the Runnable interface are
part of the standard Java libraries (java.lang package)

10

Thursday, September 22, 2011

A Program with Three Java Threads using 1st method


class A extends Thread {
public void run() {
for(int i=1;i<=5;i++) System.out.println("\t From ThreadA: i= "+i);
System.out.println("Exit from A");
}
}
class B extends Thread {
public void run() {
for(int j=1;j<=5;j++) System.out.println("\t From ThreadB: j= "+j);
System.out.println("Exit from B");
}
}
class C extends Thread {
public void run() {
for(int k=1;k<=5;k++) System.out.println("\t From ThreadC: k= "+k);
System.out.println("Exit from C");
}
}
class ThreadTest {
public static void main(String args[]) {
new A().start();
new B().start();
new C().start();
}
}
Based on Raj Buyyas slides
Thursday, September 22, 2011

11

Sample Output
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
Exit from A
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B

12

Thursday, September 22, 2011

Sample Output Run 2


From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
Exit from A
13

Thursday, September 22, 2011

Thread Priority
In Java, each thread can be assigned a priority, which
affects the order in which it is scheduled for running.
Well-written multithreaded programs should not depend on
the details of the thread scheduler policy. Any program that
relies on the thread scheduler for its correctness or
performance is likely to be nonportable between JVMs.
The best way to write a robust, responsive, portable
multithreaded application is to ensure that there are few
runnable threads at any given time. This leaves the thread
scheduler with very little choice: It simply runs the runnable
threads till they're no longer runnable. As a consequence,
the program's behavior doesn't vary much even under
radically different thread scheduling algorithms.
Effective Java, page 151
Thursday, September 22, 2011

14

Thread class
Various instance and class methods, setters and getters:
Class methods:
sleep()

Instance methods:
destroy()
interrupt()
join()
start()

Depreciated methods (unsafe and can cause deadlock)


resume(), stop() suspend()
17

Thursday, September 22, 2011

Thread.sleep causes the current thread to suspend execution


for a specified period.

Example
Sleep to print messages at four-second intervals:
public class SleepMessages {
public static void main(String args[]) throws InterruptedException {
String importantInfo[] = {
exception that sleep throws
"Mares eat oats",
when another thread
"Does eat oats",
interrupts current thread
"Little lambs eat ivy",
while sleep is active. Not
"A kid will eat ivy too"
caught in sample code.
};
for (int i = 0; i < importantInfo.length; i++) {
Thread.sleep(4000);
//Pause for 4 seconds
System.out.println(importantInfo[i]); //Print a message
}
}
}
18

Thursday, September 22, 2011

Java Synchronization
Java provides Synchronized keyword to methods that
cause only one invocation of a synchronized method on the
same object at a time.

Example
public class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
19

Thursday, September 22, 2011

Implementation of Java
synchronization
Every object has an intrinsic lock associated with it.
A thread that needs exclusive and consistent access to an
object's fields has to acquire the object's intrinsic lock
before accessing them, and then release the intrinsic lock
when it is done with them.

20

Thursday, September 22, 2011

Synchronized Statements
Unlike synchronized methods, synchronized
statements must specify the object that provides
the intrinsic lock:
Evaluate to an
Uses construct ion:
object or an
array. Used to
synchronized ( expression ) { identify lock.

statements

critical section

}
25

Thursday, September 22, 2011

Synchronized Statements
Example
public void addName(String name) {
synchronized(this) {
lastName = name;
Only this part
nameCount++;
synchronized
}
nameList.add(name);
}

26

Thursday, September 22, 2011

Atomic action
An atomic action cannot stop in the middle: it either
happens completely, or it doesn't happen at all. No side
effects of an atomic action are visible until the action is
complete.
Read/writes can be declared atomic with the volatile
keyword, e.g.
private volatile int x;
Sometimes can be more efficient than synchronized
methods.

27

Thursday, September 22, 2011

Coordinating threads
Wait/notify mechanism
Sometimes need a thread to stop running and wait for an
event before continuing.
wait() and notify() methods are methods of class Object.
Every object can maintain a list of waiting threads.
wait()
When a thread calls wait() method of an object,
any locks the thread holds are temporarily released and
thread added to list of waiting threads for that object and
stops running.
notify()
When another thread calls notify() method on
the same object, object wakes up one of the waiting threads
and allows it to continue.
28

Thursday, September 22, 2011

Join
Sometimes one thread needs to stop and wait for another
thread to complete.
join() -- waits for a thread to die, i.e. thr1.join() waits for
thread thr1 to die.

Calling return() from the run method implicitly causes the


thread to exit.

29

Thursday, September 22, 2011

Concurrency in Java 5
J2SE 5.0 (September 30, 2004).
java.util.concurrent synced a massive update.
Improved the performance of the existing primitives
(synchronized, wait(), and notify()).
Added a bunch of new powerful functionality.

September 22, 2011

Thursday, September 22, 2011

Low-level Utility Classes


Improved locking
More control, such as timed lock waits.
Higher performance and better scalability.

Atomic variables
Exposes a compare-and-set primitive which is
implemented using the fastest native construct
available on the platform.
Implemented for things like AtomicInteger,
AtomicLong, AtomicReference, AtomicBoolean.
September 22, 2011

Thursday, September 22, 2011

High-level Utility Classes


New classes:
Semaphores, mutexes, latches, barriers,
exchangers, thread pools and thread-safe
collections.

Can be used to replace synchronization,


wait(), and notify(), likely to the benefit of
performance, readability, and correctness.

September 22, 2011

Thursday, September 22, 2011

Java Concurrent Animated


A free Java application demonstrating the
concurrency utilities.
A series of animations each illustrating the
coding and usage of a component in the java
concurrent library.
Effectively a demo and a how to.
http://javaconcurrenta.sourceforge.net/

September 22, 2011

Thursday, September 22, 2011

September 22, 2011

Thursday, September 22, 2011

More information
http://java.sun.com/docs/books/tutorial/essential/
concurrency/
Java Concurrent Animated
http://javaconcurrenta.sourceforge.net/

30

Thursday, September 22, 2011

Das könnte Ihnen auch gefallen