Upload
cutler
View
44
Download
0
Embed Size (px)
DESCRIPTION
Algorithm Programming 1 89-210 Concurrent Programming in Java. Bar-Ilan University 2007-2008 תשס"ח Moshe Fresko. Threads. Definition: Thread is a single Sequential Flow of Control within a program. Other Names: Thread = Execution Context = Lightweight Process - PowerPoint PPT Presentation
Citation preview
Algorithm Programming 189-210Concurrent Programming in Java
Bar-Ilan University
תשס"ח 2007-2008
Moshe Fresko
Threads Definition: Thread is a single Sequential Flow of Control
within a program. Other Names: Thread = Execution Context = Lightweight
Process Thread like a Sequential Program, has
A beginning, a sequence, and an end. Has a single point of execution, at any given time
Threads Thread is similar to a Real Process, but runs
in a program and uses its resources, and program’s environment.
It must have some private resources like Execution Stack and Program Counter.
Multi-Threading Motivation for Multi-Threading
User-interface User can give requests while Something is running
Optimize throughput When some process is stuck in some resource like I/O
waiting for a response, others can use the CPU
Multi-Processor environment To utilize all the processors (Like in a web server)
Creating Threads In Java To create new threads in java we have
Runnable interface Thread class
Every object that will run something in a different Thread, must implement “Runnable” interface (directly or indirectly) .
interface Runnable {
void run(); }
Creating Threads In Java Thread class implements Runnable Thread.start() method: immediately returns
and starts to execute the “run()” method in a different thread.
It runs either its own run() method or its internal Runnable instance which is passed in the constructor.
Creating Threads In Java// Thread implementation in java is something like:
public class Thread implements Runnable {private Runnable target = null ; public Thread() { … }public Thread(String name) { … }public Thread(Runnable r) {
target = r ;}public Thread(String name, Runnable r) { … }public void run() {
if (target != null) { target.run();}
}// Starts the run() method in a different thread and immediately returns
public synchronized native void start();}
Creating Threads (Example)public class SimpleThread extends Thread {
private int countDown = 5; private static int threadCount = 0; public SimpleThread() {
super("" + ++threadCount); start();
} public String toString() {
return "#" + getName() + ": " + countDown; } public void run() {
while(true) { System.out.println(this); if(--countDown == 0) return;
} } public static void main(String[] args) {
for(int i = 0; i < 5; i++) new SimpleThread();
}}
Creating Threads in Java
Runnable
MyRC
Runnable
MyRC
Thread
Runnable
MyRC
SomeClass
Three possible creation of Runnable Class in Java
I II III
Creating Thread To create thread to use one of
java.lang.Thread class java.lang.Runnable interface
First Way: Using java.lang.Thread class1. Inherit from Thread in your Threading Class2. Define method run() 3. Create an object from your Threading Class4. Call start() method of it Example class MyClass extends Thread {
public void run() { /* … things to run … */ }}…MyClass m = new MyClass() ;m.start() ;
Creating Thread Second Way: Using java.lang.Runnable interface
1. Implement Runnable interface in your Class2. Define the run() method3. Create a new Object of your Class4. Create a new Thread instance by giving your Object5. Call start() method of the Thread instance Example:class MyClass implements Runnable {
public void run() { /* … things to run … */ }}…MyClass m = new MyClass() ;Thread t = new Thread(m) ;t.start() ;
If your Class has to inherit from another class other then Thread, then the only way for threading is implementing the Runnable interface,
Design Pattern : “COMMAND” Thread.start() immediately returns but creates a new
execution path that executes Runnable.run() method. It is not possible in Java to call directly a function to be
executed in a new thread. “Command” Pattern:
Encapsulates a request as an object, thereby letting you parameterize clients with different requests (and can even support undoable operations).
Thread knows only Runnable interface and Runnable.run() method. So every request to be executed should be run in run() method of a class that implements Runnable.
Design Pattern : “ADAPTER” To call an object’s method “m.f()” in a different thread
By Inheritance:class M {
public void f() { … } }class RunnableM extends M implements Runnable {
public void run() { f() ; }}
By an Adapter classclass M {
public void f() { … }}class AdapterOfM implements Runnable {
private M m ;public AdapterOfM(M m) { this.m = m ; }public void run() { m.f() ; }
} “Adapter” Pattern ( or “Wrapper” class )
Convert the interface of a class into another interface that a client expects. Adapter lets classes work together that couldn’t otherwise because of incompatible
interfaces.
Thread Control Methods void start() throw IllegalThreadStateException
Creates a thread and starts the run() method in it static void sleep(long sleepTimeInMiliseconds) throws
InterruptedException interrupt() from outside can wake it up by causing it to throw
InterruptedException void join() throws InterruptedException
Waits for a thread to finish its job static void yield()
Gives other threads with same priority the possibility to get CPU boolean isAlive() – true if the thread is not dead Two more from Object
Object.wait() Object.notify()
Thread States Newly Created State
new MyThread() Runnable State
After calling start() in which run() is executed Logically it is running, but physically it can be in one of the two states
Running State (Physically running on CPU) Queued State (Waiting for its turn)
Blocked State Enters to Blocked State if the thread …
… calls an objects wait() method … calls sleep() method … waits for I/O … will join() with another thread
Exits from Blocked State if the thread … … is waiting for an object, and on that object notify() or notifyAll() is called … is sleeping and the sleeping time elapsed … is waiting for I/O, and I/O is completed
Dead State When finishes the run() process
Synchronization Access to same object from different threads concurrently
can create problems. Read-Read Conflicts : Mostly no-problem Read-Write Conflicts Write-Write Conflicts
“synchronized” keyword in java can give exclusive access in object level
Only one thread can be found in a synchronized method or a synchronized code section of an object.
Synchronization “synchronized” keyword can be used in a
several places. It locks an OBJECT for a BLOCK of code. Whenever this thread is in that BLOCK, other
threads cannot enter into any block that needs the locking (synchronization) of that same OBJECT.
Using “synchronize” keyword1. Before any non-static method definition
It locks this object until the end of the method block.
class M {synchronized void f() {
// It will lock this M instance …// It will unlock back this M
instance}
}
Using “synchronize” keyword2. Within any block of code
It locks the given object until the end of the block. …
M m = new M() ;
…
synchronized( m ) {
// It will lock the object referenced by m
…
// It will unlock back the object m
}
Using “synchronize” keyword3. Before any static method definition
It locks this.getClass() object until the end of the method block.Every class definition has an instance of “Class” class associated with it. It can be reached by getClass() method of any instance. It is that specific Class instance that it locks.class M {
synchronized static void f() {// It will lock the class M…// It will unlock back the class M
}}
Using “synchronize” keyword4. Static level synchronization within any block
To lock static level synchronization within a block the getClass() method can be used to get the instance of Class associated with any class.
…M m = new M() ;…synchronized( m.getClass() ) { // or
( M.class )// It will lock the class M …// It will unlock back the class M
}
Synchronization Object Level Synchronization
class MyClass {synchronized void method1() { …A… }synchronized void method2() { …B… }void method3() {
… synchronized(this) {
…C…}…
}}…MyClass m = new MyClass() ;m.method1() ; // synchronized on mm.method3() ; // partly synchronized on msynchronized(m) { …D… } // synchronized on m
Only one thread can be in one of the sections A,B,C,and D, for a single object m.
Synchronization Class based Synchronization
class MyClass {static synchronized void method3() { …A… }
}…MyClass m1 = new MyClass();MyClass m2 = new MyClass() ;…synchronized(m1.getClass()) { …B… }…synchronized(m2.getClass()) { …C… }…
Only one thread can be in one of the sections A,B and C
Multi-tasking problems Starvation (Contention):
When a thread fails to run in Runnable state.A thread cannot get CPU resource since other threads or processes are getting it.
Dormancy: A non-runnable thread fails to become runnable.
When a thread stays in a wait(), while there is no other thread that makes notify() for that object.
Deadlock: Two or more threads block each other.Thread 1 locks the object a, and waits for object b.Thread 2 locks the object b, and waits for object a.