Threads in Python Programming
Threads in Python Programming
OBJECT-ORIENTED PROGRAMMING II
Threads in Java
• Two tasks
Multiprocessing (Multithreading)
• Approach
• Multiple processing units (multiprocessor)
• Computer works on several tasks in parallel
• Performance can be improved
Dual-core 32
Titan at
AMD processor
ORNL
Athlon X2 Pentium
Xeon
Perform Multiple Tasks Using Processes
• Process
• Definition à executable program loaded in memory
• Has own address space
• Variables & data structures (in memory)
• Each process may execute a different program
• Communicate via operating system, files, network
• May contain multiple threads
Perform Multiple Tasks Using Threads
• Thread
• Definition à sequentially executed stream of instructions
• Has own execution context
• Program counter, call stack (local variables)
• Communicate via shared access to data
• Also known as “lightweight process”
Motivation for Multithreading
• Captures logical structure of problem
• May have concurrent interacting components
• Can handle each component using separate thread
• Simplifies programming for problem
• Example
• Multithreading
• Executing program with multiple threads in parallel
• Special form of multiprocessing
Creating Threads in Java
• Two approaches to create threads
• Extending Thread class (NOT RECOMMENDED)
• Runnable interface approach (PREFERED)
• Approach 1: Extending Thread class
• We overload the Thread class run() method
• The run() methods defines the actual task the thread performs
• Example
public class MyT extends Thread {
public void run( ) {
… // work for thread
}
}
MyT t = new MyT( ) ; // create thread
t.start( ); // begin running thread
… // thread executing in parallel
• Example: message, messageThreadExtends packages
Creating Threads in Java
• Approach 2: Runnable Interface
• Define a class (worker) that implements the Runnable interface
public interface Runnable {
public void run(); // work done by thread
}
• Create thread to execute the run() method
• Alternative 1: Create thread object and pass worker object to Thread
constructor
• Alternative 2: Hand worker object to an executor
• Example
public class Worker implements Runnable {
public void run( ) { // work for thread }
}
Thread t = new Thread(new Worker( )); // create thread
t.start(); // begin running thread
… // thread executing in parallel
• Example: message, messageThreadRunnable packages
Why Extending Thread Approach Not Recommended?
• Not a big problem for getting started
• But a bad habit for industrial strength development
• Methods of worker and Thread class intermixed
• Hard to migrate to more efficient approaches
• Thread Pools
Thread Class
public class Thread extends Object implements Runnable {
public Thread();
public Thread(String name); // Thread name
public Thread(Runnable R);
public Thread(Runnable R, String name);
• Runnable is interface
• So it can be implemented by any class
• Required for multithreading in applets
new start
notify, notifyAll,
new runnable
IO complete,
sleep expired,
scheduler yield, join complete
time
slice
running blocked
IO, sleep,
terminate wait, join
dead
• Scheduling policy
• Non-preemptive (cooperative) scheduling
• Preemptive scheduling
Threads – Non-preemptive Scheduling
• Threads continue execution until
• Thread terminates
• Executes instruction causing wait (e.g., IO)
• Thread volunteering to stop (invoking yield or sleep)
Threads – Preemptive Scheduling
• Threads continue execution until
• Same reasons as non-preemptive scheduling
• Preempted by scheduler
Thread Scheduling Observations
• Order thread is selected is indeterminate
• Depends on scheduler
• Scheduling may not be fair
• Some threads may execute more often
• Thread can block indefinitely (starvation)
• If other threads always execute first
• Your code should work correctly regardless the
scheduling policy in place
Java Thread Example
public class ThreadNoJoin extends Thread {
public void run() {
for (int i = 0; i < 3; i++) {
try {
sleep((int)(Math.random() * 5000)); // 5 secs
} catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(i);
}
}
public static void main(String[] args) {
Thread t1 = new ThreadNoJoin();
Thread t2 = new ThreadNoJoin();
t1.start();
t2.start();
System.out.println("Done");
}
}