• Multiprocessing granularity – Using Multiple Processors. • Multiprogramming (Batch) – Switch and execute different jobs simultaneously, to improve CPU utilization. Concurrent Programming • Multitasking (Interactive) – Perform more than one task at a time for each user, class Thread to improve response time. • Multithreading interface Runnable – Threads in a user task (process) can share code, data, class Object and system resources, and access them concurrently. – Each thread has a separate program counter, registers, and a run-time stack. cs480 (Prasad) L11Threads 1 cs480 (Prasad) L11Threads 2 Multitasking Browser : A Multithreaded Application • Concurrent Activities: ls ls – Scrolling a page. more a.txt xclock & – Downloading an applet/image over the internet. emacs -nw a.java netscape & – Playing animation and sound simultaneously. gcc a.c ; emacs a.java & – Printing a page in the background. javac a.java ; – Updating Stock Quotes automatically. a.out … – FTP-ing a remote file. java a – ... logout ... • Browser is a mini-OS! cs480 (Prasad) L11Threads 3 cs480 (Prasad) L11Threads 4
Motivation Threads in Java Application independent interleaving of threads. • A single sequential flow of control • Support Concurrent Activities (of execution of expressions and • Multimedia Applications statements) is called a thread . • Advertisements, Sports/stocks ticker • A thread independently executes Java • Improve user response code, but may share address space with other threads. (cf. Process) • User input in interactive programs • I/O in networked programs “in the background” Java primitives for concurrent programming • Improve CPU utilization are based on Hoare’s monitors . • Demand-driven thread-scheduling cs480 (Prasad) L11Threads 5 cs480 (Prasad) L11Threads 6 Java Primitives Overall Game Plan • Mutual exclusion • synchronized methods in a class cannot be run • How to create and execute multiple threads? concurrently on behalf of different threads. • Interleaved computations • synchronized statement locks an object. • Indiscriminate interleaving interferes with • “Object” is an instance of a class application semantics ( incl. class Class ). • Introduce Mutual Exclusion constucts • Synchronization / Cooperation • Example : Printing documents on a shared printer • Methods wait(), notify(), notifyAll() etc. • Introduce Synchronization constructs in class Object enable threads to communicate and regulate each other’s progress. • Example : Buffering on a shared printer cs480 (Prasad) L11Threads 7 cs480 (Prasad) L11Threads 8
Creating and Running Threads • Define subclass of class Thread . Override run() method. Creating Threads public void run() { } • Create an instance of the subclass, and invoke start() on it. Now run() method executes in an independent thread . cs480 (Prasad) L11Threads 9 cs480 (Prasad) L11Threads 10 Example using class Thread Windows > javac Echo.java > java Echo class Echo extends Thread { with yield() 1 ABC int id; 1 ABC 1 ABC Echo(int i) { 2 ABC in both OS Solaris 1 ABC 2 ABC id = i; 1 ABC 2 ABC } 1 ABC 2 ABC 1 ABC public void run() { 1 ABC 2 ABC 2 ABC 1 ABC while (true) { 1 ABC 1 ABC 2 ABC System.out.println(id +“ ABC ”); 2 ABC 1 ABC 2ABC 2 ABC // yield(); 2 ABC 1 ABC 1 ABC 2 ABC } 2 ABC 1 ABC 2 ABC 1 ABC } 2 ABC 1 ABC 1ABC 1 ABC public static void main ( String[] args ) { 2 ABC 2 ABC 1 ABC 2 ABC new Echo(1) . start(); 1 ABC 1 ABC 1 ABC 2 ABC new Echo(2) . start(); 1 ABC 1 ABC 2 ABC 2 ABC } 1 ABC ... ... 1 ABC } ... . . . cs480 (Prasad) L11Threads 11 cs480 (Prasad) L11Threads 12
Example using interface Runnable Alternative :Creating and Running Threads class Echo implements Runnable { int id; Echo(int i) { id = i; } public void run() { • Threads can also be created from an while (true) { System.out.println(id +“ ABC ”); instance of a class implementing the // yield(); interface Runnable . } } • Required when the class is defined by public static void main ( String[] args ) { new Thread (new Echo(1)) . start(); extension. new Thread (new Echo(2)) . start(); } } cs480 (Prasad) L11Threads 13 cs480 (Prasad) L11Threads 14 Same Example in C# Alternate Rendition in Java using System.Threading; class Echo implements Runnable { public void run() { class Echo { try { int id; while (true) { Echo(int i) { Thread.sleep(1000); id = i; System.out.println(“ABC”); } } public void run() { } catch (InterruptedException e) { while (true) return; System.Console.WriteLine(id + " ABC "); } } public static void Main () { } new Thread ( new ThreadStart public static void main (String[] args) { (new Echo(1).run)) . Start(); Runnable r = new Echo(); new Thread ( new ThreadStart new Thread(r) . start(); (new Echo(2).run)) . Start(); } } } } cs480 (Prasad) L11Threads 15 cs480 (Prasad) L11Threads 16
class Ball { static final int TOP = 10, BOTTOM = 150; int incr = 2; int ypos = TOP; void paint(java.awt.Graphics g) { Threads and Applets if (ypos < TOP || ypos > BOTTOM) incr= -incr; ypos += incr; A Simple Bouncing Ball Animation g.setColor(java.awt.Color.cyan); g.fillOval(10,ypos, 10,10); }} cs480 (Prasad) L11Threads 17 cs480 (Prasad) L11Threads 18 // <applet code=Bounce.class height=200 width=50></applet> Threaded Applet public class Bounce extends java.applet.Applet { public class ThreadedBounce Ball b; extends java.applet.Applet public void init() { implements Runnable { b = new Ball(); Ball b; setBackground(java.awt.Color.red); Thread t; } public void init() { public void paint(java.awt.Graphics g) { b.paint(g); b = new Ball(); repaint(15); setBackground (java.awt.Color.red); /* try { while (true) { t = new Thread(this); Thread.sleep(15); repaint(); t.start(); } } catch (InterruptedException e) {}; */ } } } ... cs480 (Prasad) L11Threads 19 cs480 (Prasad) L11Threads 20
Another version of Threaded Applet ... public class ThreadedColorBounce public void paint(java.awt.Graphics g) { extends java.applet.Applet b.paint(g); implements Runnable { // moved the code from here Ball b; } Thread t; public void run() { public void init() { try { b = new Ball(); while (true) { setBackground(java.awt.Color.red); Thread.sleep(15); } repaint(); public void start() { } if ( t == null) { } catch (InterruptedException e) {}; t = new Thread(this); } t.start(); } }} ... cs480 (Prasad) L11Threads 21 cs480 (Prasad) L11Threads 22 Color Changing Ball public void stop() { class ColorBall extends Thread { t = null; static final int TOP = 10, BOTTOM = 150; } java.awt.Color c = java.awt.Color.cyan; public void paint(java.awt.Graphics g) { int incr = 2; b.paint(g); int ypos = TOP; } public ColorBall(){ public void run() { start(); try { } void paint(java.awt.Graphics g) { while (true) { if (ypos < TOP || ypos > BOTTOM) Thread.sleep(15); incr= -incr; repaint(); ypos += incr; } g.setColor(c); } catch (InterruptedException e) {}; g.fillOval(10,ypos, 10,10); } ... } } cs480 (Prasad) L11Threads 23 cs480 (Prasad) L11Threads 24
... public void run() { try { while (true) { sleep(600); Mutual Exclusion c = new java.awt.Color( (float) Math.random(), (float) Math.random(), (float) Math.random() ); Sharing Data } } catch (InterruptedException e) {}; } } cs480 (Prasad) L11Threads 25 cs480 (Prasad) L11Threads 26 class SharingThread extends Thread { Threads Sharing Data private static Shared s = new Shared(); String Id; class Shared { SharingThread (String Name) { private int cnt = 0; Id = Name; // synchronized void print(String Id) { start(); System.out.print(Id + “:” + cnt ); } System.out.println( “-” + ++cnt); public void run () { } while (true) { } class Shared { s.print(Id); // yield(); private int cnt = 0; } void print(String Id) { } synchronized (this) { public static void main ( String [] args ) { System.out.print(Id + “:” + cnt ); new SharingThread(“A”) ; System.out.println( “-” + ++cnt); } new SharingThread(“B”) ; } } } } cs480 (Prasad) L11Threads 27 cs480 (Prasad) L11Threads 28
Recommend
More recommend