1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing, The composite design pattern.

Slides:



Advertisements
Similar presentations
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Advertisements

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Multithreading The objectives of this chapter are:
Big Picture Lab 4 Operating Systems Csaba Andras Moritz.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© 2004, D. J. Foreman 2-1 Concurrency, Processes and Threads.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Multithreading.
Chapter 51 Threads Chapter 5. 2 Process Characteristics  Concept of Process has two facets.  A Process is: A Unit of resource ownership:  a virtual.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 Advanced Computer Programming Concurrency Multithreaded Programs Copyright © Texas Education Agency, 2013.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Lecture 4 : JAVA Thread Programming
Processes and Threads.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
1 Java Threads Instructor: Mainak Chaudhuri
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Multithreading in Java Project of COCS 513 By Wei Li December, 2000.
1 Processes, Threads, Race Conditions & Deadlocks Operating Systems Review.
© 2004, D. J. Foreman 2-1 Concurrency, Processes and Threads.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Concurrent Programming. Concurrency  Concurrency means for a program to have multiple paths of execution running at (almost) the same time. Examples:
1 Web Based Programming Section 8 James King 12 August 2003.
Games Development 2 Concurrent Programming CO3301 Week 9.
CS Lecture 00 Swing overview and introduction Lynda Thomas
Threads.
CS333 Intro to Operating Systems Jonathan Walpole.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Multithreading [Modified]
Java Thread and Memory Model
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
3/12/2013Computer Engg, IIT(BHU)1 OpenMP-1. OpenMP is a portable, multiprocessing API for shared memory computers OpenMP is not a “language” Instead,
Slides created by: Professor Ian G. Harris Operating Systems  Allow the processor to perform several tasks at virtually the same time Ex. Web Controlled.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
1 Critical Section Problem CIS 450 Winter 2003 Professor Jinhua Guo.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
1 Chapter 5: Threads Overview Multithreading Models & Issues Read Chapter 5 pages
Multithreading / Concurrency
Multi-processor Scheduling
Java Multithreading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Concurrency, Processes and Threads
CS399 New Beginnings Jonathan Walpole.
Object-Orientated Analysis, Design and Programming
Computer Engg, IIT(BHU)
Multithreading.
Thread Implementation Issues
Threads Chapter 4.
CS510 Operating System Foundations
Threads and Multithreading
Concurrency, Processes and Threads
Lecture 19 Threads CSE /6/2019.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing, The composite design pattern

2 Last Lecture More design by abstraction.. –Design patterns the Strategy pattern (again) –Making use of interfaces the Factory pattern –making use of abstract classes and inheritance the Adapter design pattern –A concrete case study An algorithm animator Applying the Template, Strategy, Observer-Observable and the Factory patterns

3 Today’s Talk Multithreading in Java programs –Concurrency –Thread control and modes of threads –Critical regions and data hazards –Synchronize and atomicity –Concurrent in the Java API Simple example with concurrent counters AWT, Swing and the composite pattern

4 Multi-threaded programming Multi-threaded programs –Simultaneously executing threads can run either sequentially on single processor concurrently using multiple processors –Processor allocation is dependent on the operating system

5 Concurrency A sequential program –A single thread executing on one processor, running one instruction at a time A concurrent program –Multiple threads (logically) executed in parallel The implementation of a program with multiple threads can be –Multiprogramming Threads share one processor (time multiplexing) –Multiprocessing Threads are multiplexed and executed on multiprocessors or multicores –Distributed processing Processes distributed and executed on different machines

6 Multi-threading in Java Threads are objects –Instances of the java.lang.Thread class A threaded object extends Thread or... implements the Runnable interface All threads executed by the JVM share memory space –The heap For data allocation (fields, variables,...) –Stacks One for each thread (method arguments, return values...) Threads can communicate through shared variables and objects allocated on the heap

7 Dissecting the memory Program code Static data Heap Thread stacks shared data space references

8 A Concurrent Counter public class Counter1 extends Thread{ static int id = 0; int value, bound, delay, myid; public Counter1(int start, int stop, int d){ value = start; bound = stop; delay = d; myid = id; ++id; } public void run(){ while(value < bound){ System.out.println("" + myid +": " + value + " "); value++; try{ sleep(delay); } catch(InterruptedException ie){ ie.printStackTrace();} } ….

9 Counter1 output (class Counter1 continued.) public static void main(String[] args) { new Counter1(0, 50, 20).start(); } jabba% java Counter1 T0:0, T1:0, T0:1, T1:1, T0:2, T1:2, T0:3, T1:3, T0:4, T1:4, T0:5, T1:5, T0:6, T1:6, T0:7, T1:7, T0:8, T1:8, T0:9, T1:9, T0:10, T1:10, T0:11, T1:11, T0:12, T1:12, T0:13, T1:13, T0:14, T1:14, T0:15, T1:15, T0:16, T1:16, T0:17, T1:17, T0:18, T1:18, T0:19, T1:19, T0:20, T1:20, T0:21, T1:21, T0:22, T1:22, T0:23, T1:23, T0:24, T1:24, T0:25, T1:25, T0:26, T1:26, T0:27, T1:27, T0:28, T1:28, T0:29, T1:29, T0:30, T1:30, T0:31, T1:31, T0:32, T1:32, T0:33, T1:33, T0:34, T1:34, T0:35, T1:35, T0:36, T1:36, T0:37, T1:37, T0:38, T1:38, T0:39, T1:39, T0:40, T1:40, T0:41, T1:41, T0:42, T1:42, T0:43, T1:43, T0:44, T1:44, T0:45, T1:45, T0:46, T1:46, T0:47, T1:47, T0:48, T1:48, T0:49, T1:49

10 Multiple Counter Threads public class Concurrent Counters{ public static void main(String args[]){ for(int i = 0; i<5; i++){ new Counter1(0,20,50).start(); } How many Thread s are running now?

11 Controlling Threads Thread execution is managed by the JVM –Scheduled by priority (an integer value) –Threads with equal priority will be executed in arbitrary order No fairness guarantee (fair amount of processor time) The scheduling can also be affected by the programmer –by setting thread priorities Can be done dynamically (at runtime) –by blocking or yielding sleep(); yield;... join();

12 Blocked and Runnable Blocked mode –Thread sleeps or waits for other threads to finish sleep(milliseconds); –Runnable state -> Blocked state (block until time t) join(); –Runnable state -> Blocked state (block untill thread ”dies”) Runnable mode –Ready to be scheduled and run yield(); –Runnable state -> Runnable state (release execution) interrupt(); –Blocked -> Runnable or Runnable with IR-flag

13 Modes of Threads

14 Concurrent Counter 2 public class Counter2 extends Thread{ static int id = 0; int value, bound, delay, myid; public Counter2(int start, int stop, int d){ value = start; bound = stop; delay = d; myid = id; ++id; } public void run(){ while(value < bound){ System.out.println("Thread nbr " + myid +": " + value); value++; yield(); /** Release and force blocked mode **/ }

15 Counter2 output (class Counter2 continued.) public static void main(String[] args) { new Counter2(0, 50, 20).start(); } jabba% java Counter2 T0:0, T1:0, T0:1, T1:1, T0:2, T1:2, T0:3, T1:3, T0:4, T1:4, T0:5, T1:5, T0:6, T1:6, T0:7, T1:7, T0:8, T1:8, T0:9, T1:9, T0:10, T1:10, T0:11, T1:11, T0:12, T1:12, T0:13, T1:13, T0:14, T1:14, T0:15, T1:15, T0:16, T1:16, T0:17, T1:17, T0:18, T1:18, T0:19, T1:19, T0:20, T1:20, T0:21, T1:21, T0:22, T1:22, T0:23, T1:23, T0:24, T1:24, T0:25, T1:25, T0:26, T1:26, T0:27, T1:27, T0:28, T1:28, T0:29, T1:29, T0:30, T1:30, T0:31, T1:31, T0:32, T1:32, T0:33, T1:33, T0:34, T1:34, T0:35, T1:35, T0:36, T1:36, T0:37, T1:37, T0:38, T1:38, T0:39, T1:39, T0:40, T1:40, T0:41, T1:41, T0:42, T1:42, T0:43, T1:43, T0:44, T1:44, T0:45, T1:45, T0:46, T1:46, T0:47, T1:47, T0:48, T1:48, T0:49, T1:49

16 Concurrent Counter 3 public class Counter3 extends Thread{ static int id = 0; int value, bound, delay, myid; public Counter3(int start, int stop, int d){ value = start; bound = stop; delay = d; myid = id; ++id; } public void run(){ while(value < bound){ System.out.println("Thread nbr " + myid +": " + value); value++; yield(); }

17 Synchronising with join() public class Concurrent Counter3{ for(int i = 0; i<10; i++){ Counter3 cnt = new Counter3(0,20,50); cnt.start(); try{ cnt.join(); } catch(InterruptedException ie){} } In what order will threads be executed now?

18 Counter3 output jabba% java Counter3 T0:0, T0:1, T0:2, T0:3, T0:4, T0:5, T0:6, T0:7, T0:8, T0:9, T0:10, T0:11, T0:12, T0:13, T0:14, T0:15, T0:16, T0:17, T0:18, T0:19, T1:0, T1:1, T1:2, T1:3, T1:4, T1:5, T1:6, T1:7, T1:8, T1:9, T1:10, T1:11, T1:12, T1:13, T1:14, T1:15, T1:16, T1:17, T1:18, T1:19, T2:0, T2:1, T2:2, T2:3, T2:4, T2:5, T2:6, T2:7, T2:8, T2:9, T2:10, T2:11, T2:12, T2:13, T2:14, T2:15, T2:16, T2:17, T2:18, T2:19, T3:0, T3:1, T3:2, T3:3, T3:4, T3:5, T3:6, T3:7, T3:8, T3:9, T3:10, T3:11, T3:12, T3:13, T3:14, T3:15, T3:16, T3:17, T3:18, T3:19, T4:0, T4:1, T4:2, T4:3, T4:4, T4:5, T4:6, T4:7, T4:8, T4:9, T4:10, T4:11, T4:12, T4:13, T4:14, T4:15, T4:16, T4:17, T4:18, T4:19, T5:0, T5:1, T5:2, T5:3, T5:4, T5:5, T5:6, T5:7, T5:8, T5:9, T5:10, T5:11, T5:12, T5:13, T5:14, T5:15, T5:16, T5:17, T5:18, T5:19, T6:0, T6:1, T6:2, T6:3, T6:4, T6:5, T6:6, T6:7, T6:8, T6:9, T6:10, T6:11, T6:12, T6:13, T6:14, T6:15, T6:16, T6:17, T6:18, T6:19, T7:0, T7:1, T7:2, T7:3, T7:4, T7:5, T7:6, T7:7, T7:8, T7:9, T7:10, T7:11, T7:12, T7:13, T7:14, T7:15, T7:16, T7:17, T7:18, T7:19, T8:0, T8:1, T8:2, T8:3, T8:4, T8:5, T8:6, T8:7, T8:8, T8:9, T8:10, T8:11, T8:12, T8:13, T8:14, T8:15, T8:16, T8:17, T8:18, T8:19, T9:0, T9:1, T9:2, T9:3, T9:4, T9:5, T9:6, T9:7, T9:8, T9:9, T9:10, T9:11, T9:12, T9:13, T9:14, T9:15, T9:16, T9:17, T9:18, T9:19,

19 Critical regions Pieces of code that is reading and writing shared data, and accessed by multiple threads, constitute a critical region –Race hazards between threads when writing to shared data Java provide the synchronized keyword for atomic access to methods

20 What is a race hazard? Multiple threads concurrently access same data At least one access is a write Thread 1: x = x+1; Thread 2: x = x+2;

21 Avoiding data races Thread 1: lock(l); x = x+1; unlock(l); Thread 2: lock(l); x = x+2; unlock(l);

22 Critical regions public class Account{ private int balance; public Account(){ balance = 0;} public boolean insert(int amount){... } public boolean withDraw(int amount){ if(balance >= amount){ newBalance = balance - amount; balance = newBalance; return true; } else { return false; } } Critical region

23 A synchronized withDraw() public class Account{ private int balance; public Account(){ balance = 0;} public boolean insert(int amount){... } public synchronized boolean withDraw(int amount){ if(balance >= amount){ newBalance = balance - amount; balance = newBalance; return true; } else { return false; } }

24 insert() and withDraw() public class Account{ private int balance; public Account(){ balance = 0;} public synchronized boolean insert(int amount){ int newBalance = balance + amount; balance = newBalance; } public synchronized boolean withDraw(int amount){ if(balance >= amount){ int newBalance = balance - amount; balance = newBalance; return true; }else { return false; } } Using both synchronized insert and withDraw, are we safe?

25 Atomicity in balance public class Account{ private AtomicInteger balance;//Atomic Integer public Account(){ balance = new AtomicInteger(); } public synchronized void insert(int amount){ balance.addAndGet(amount);// Atomic access to balance } public synchronized boolean withDraw(int amount){ int status = balance.get();// Enough money available? if(status >= amount){ balance.set(status - amount);// withdraw return true;// return success } return false,// No money left  }

26 Java.util.concurrent Concurrent Data structures –ArrayBlockingQueue For threadsafe bounded queues –ConcurrentHashMap Threadsafe hashmap –ConcurrentLinkedQueue For unbounded threadsafe queues –... Barriers and Semaphores –CyclicBarrier Common barrier point allowing Threads to wait for each other Cyclic means that the Barrier object can be reused –Semaphore To permit access only for a restricted number of Threads –...

27 Java.util.concurrent.atomic Atomic Classes and wrappers –AtomicBoolean –AtomicInteger –AtomicIntegerArray –AtomicLong –AtomicReference –...

28 A Few words about AWT and Swing

29 Graphical User Interfaces in Java There are two packages in the Java API –Abstract Windows Toolkit (AWT) Provides basic support for GUI development AWT components are ”heavyweight” (Looks and behaves as the underlying OS windows system) –SWING Extension of AWT, a bit more sophisticated and extensive than AWT Most components are ”Lightweight” (Java runtime environment, not OS dependant look)

30 Four ”main” class categories Components –Each visible GUI object is of Component type LayoutManagers –Determines how components are placed within an outer container Events and EventListeners –Java user interaction is event driven (inputs or actions) Graphics and Imaging Classes –Provides methods to draw images, texts and shapes

31 Design patterns widely used Common used patterns are –Strategy Layoutmanager implements strategy pattern for placing components Some concrete strategys: FlowLayout, BorderLayout, GridLayout etc... –Template Examples are: Component, MouseAdapters Let us define methods like paint, update, dealing with mouse actions. etc. –Composite Combines several components uniformly

32 Design pattern: Composite The composite pattern is a pattern for creating hierarchical structures of objects –Components that contain other components We can treat a combination of several components as one uniform object –Example: A ButtonPanel containing Buttons.. –A Frame with Buttons and Drawing space

33 Structure of the Composite pattern

34 LayoutManager

35 Event handling in Java Users interact with a program through Event objects –Click in the mouse, typing text etc... In Java, EventListeners are used to detect Events so we can assign the proper action When an Event occur, program execution is transferred to the listener object –ex. actionPerformed(Event e)

36 The Event handling process 1. When an Event has occurred, the JVM determines the source and the type 2. If there is any Listener for this event, an Action Event is instantiated 3. For each Listener that match the event, JVM calls the event handling method, passing the Event object