0% found this document useful (0 votes)
6 views

Parallel Computing - Lecture 3

كتاب

Uploaded by

karimsal1430
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Parallel Computing - Lecture 3

كتاب

Uploaded by

karimsal1430
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Lecture

Multithreaded Programming
Program with master and
children threads
Threads Concept
Multiple Thread 1

threads on
Thread 2
Thread 3

multiple CPUs

Multiple threads Thread 1

sharing a single
Thread 2
Thread 3

CPU

3
THREADS IN JAVA
Threads are objects in the Java language. They can be created by using
two different mechanisms:
1. Create a class that extends the standard Thread class.
2. Create a class that implements the standard Runnable interface.
THREADS IN JAVA
• Thread can be defined by:
• Extending the java.lang.Thread class, or
• Implementing the java.lang.Runnable interface.
• The run() method should be overridden and should contain the code
that will be executed by the new thread.
• This method must be public with a void return type and should not
take any arguments.
Extending the Thread Class
1. Create a class by extending the Thread class and override the run()
method:
class MyThread extends Thread {
public void run() {
// thread body of execution
}
}
2. Create a thread object:
MyThread thr1 = new MyThread();
3. Start Execution of created thread:
thr1.start();
Example
/* ThreadEx1.java: A simple program creating and invoking a thread object by
extending the standard Thread class. */
class MyThread extends Thread {
public void run() {
System.out.println(“ this thread is running ... ”);
}
}
class ThreadEx1 {
public static void main(String [] args ) {
MyThread t = new MyThread();
t.start();
}
}
Implementing the Runnable
Interface
1. Create a class that implements the interface Runnable and override run() method:
class MyThread implements Runnable {

public void run() {
// thread body of execution
}
}
2. Creating Object:
MyThread myObject = new MyThread();
3. Creating Thread Object:
Thread thr1 = new Thread(myObject);
4. Start Execution:
thr1.start();
Example
/* ThreadEx2.java: A simple program creating and invoking a thread object by
implementing Runnable interface. */
class MyThread implements Runnable {
public void run() {
System.out.println(“ this thread is running ... ”);
}
}
class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
t.start();
}
}
Life Cycle of Thread
new
start()
I/O completed

ready resume()
Time expired/
notify() interrupted

sleeping blocked
waiting
dispatch
sleep()
wait() suspend()
running Block on I/O
completion

stop() dead 10
Thread States

http://www.deitel.com/articles/java_tutorials/20051126/JavaMultithreading_Tutorial_Part2.html

11
Thread States

A thread can be in one of five states: New,


Ready, Running, Blocked, or Finished.

yield(), or Running
time out run() returns
Thread created start()
New Ready run() join() Finished

interrupt() sleep()
Target wait()
finished

Wait for target Wait for time Wait to be


to finish out notified
Time out notify() or
notifyAll()
Blocked
Interrupted()

12
Thread termination
A thread becomes Not Runnable when one of these events occurs:

• Its sleep method is invoked.


• The thread calls the wait method to wait for a specific condition to be
satisifed.
• The thread is blocking on I/O.

13
Threads
• Threads are lightweight processes as the overhead of switching
between threads is less
• They can be easily spawned
• The Java Virtual Machine spawns a thread when your program is run
called the Main Thread
Why do we need threads?
• To enhance parallel processing
• To increase response to the user
• To utilize the idle time of the CPU
• Prioritize your work depending on priority
Example
• Consider a simple web server
• The web server listens for request and serves it
• If the web server was not multithreaded, the requests processing
would be in a queue, thus increasing the response time and also
might hang the server if there was a bad request.
• By implementing in a multithreaded environment, the web server can
serve multiple request simultaneously thus improving response time
Creating threads
• In java threads can be created by extending the Thread class or
implementing the Runnable Interface
• It is more preferred to implement the Runnable Interface so that we
can extend properties from other classes
• Implement the run() method which is the starting point for thread
execution
Running threads
• Example
class mythread implements Runnable{
public void run(){
System.out.println(“Thread Started”);
}
}

class mainclass {
public static void main(String args[]){
Thread t = new Thread(new mythread()); // This is the way to instantiate a thread
implementing runnable interface
t.start(); // starts the thread by running the run method
}
}

• Calling t.run() does not start a thread, it is just a simple method call.
• Creating an object does not create a thread, calling start() method creates the thread.
Synchronization
• Synchronization is prevent data corruption
• Synchronization allows only one thread to perform an operation on a
object at a time.
• If multiple threads require an access to an object, synchronization
helps in maintaining consistency.
Example
public class Counter{
private int count = 0;
public int getCount(){
return count;
}

public setCount(int count){


this.count = count;
}
}
• In this example, the counter tells how many an access has been made.
• If a thread is accessing setCount and updating count and another thread is accessing getCount at the same time, there will
be inconsistency in the value of count.
Fixing the example
public class Counter{
private static int count = 0;
public synchronized int getCount(){
return count;
}

public synchoronized setCount(int count){


this.count = count;
}
}
• By adding the synchronized keyword we make sure that when one thread is in the
setCount method the other threads are all in waiting state.
What about static methods?
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}

public static synchronized setCount(int count){


this.count = count;
}
}
• In this example the methods are static and hence are associated with the class and not the instance.
• Hence the lock is placed on the class object that is, Counter.class object and not on the object itself. Any other non static
synchronized methods are still available for access by other threads.
Common Synchronization mistake
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}

public synchronized setCount(int count){


this.count = count;
}
}
• The common mistake here is one method is static synchronized and another method is non static synchronized.
• This makes a difference as locks are placed on two different objects. The class object and the instance and hence two
different threads can access the methods simultaneously.
THANKS

You might also like