




















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





















Problem
Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files to disk Perform useful computation (editor, browser, game)
Multitasking Multiprocessing
Multitasking Can Aid Performance
Multiprocessing (Multithreading)
Multiple processing units (multiprocessor) Computer works on several tasks in parallel Performance can be improved 4096 processor Cray X 32 processor Pentium Xeon Dual-core AMD Athlon X
Perform Multiple Tasks Using…
Definition – sequentially executed stream of instructions Shares address space with other threads Has own execution context Program counter, call stack (local variables) Communicate via shared access to data Multiple threads in process execute same program Also known as “lightweight process”
Web Server uses threads to handle … Multiple simultaneous web browser requests Motivation for Multithreading
May have concurrent interacting components Can handle each component using separate thread Simplifies programming for problem
Multithreading Overview
Creating Java threads Thread states Scheduling
Data races Locks Wait / Notify
Programming with Threads
Writing programs divided into independent tasks Tasks may be executed in parallel on multiprocessors
Executing program with multiple threads in parallel Special form of multiprocessing
Thread Class public class Thread { public Thread(Runnable R); // Thread ⇒ R.run() public Thread(Runnable R, String name); public void start(); // begin thread execution ... }
More Thread Class Methods public class Thread { … public String getName(); public void interrupt(); public boolean isAlive(); public void join(); public void setDaemon(boolean on); public void setName(String name); public void setPriority(int level); public static Thread currentThread(); public static void sleep(long milliseconds); public static void yield(); }
Alternative (Not Recommended)
public class MyT extends Thread { public void run() { … // work for thread } } MyT t = new MyT(); // create thread t.start(); // begin running thread
Why not recommended?
but a bad habit for industrial strength development
Threads – Thread States State diagram new runnable terminated blocked new start terminate IO, sleep, join, request lock IO complete, sleep expired, join complete, acquire lock
Threads – Scheduling
Determines which runnable threads to run Can be based on thread priority Part of OS or Java Virtual Machine (JVM) Many computers can run multiple threads simultaneously (or nearly so)