+ All Categories
Home > Documents > 1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing,...

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

Date post: 05-Jan-2016
Category:
Upload: damon-rich
View: 214 times
Download: 0 times
Share this document with a friend
36
1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing, The composite design pattern
Transcript
Page 1: 1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing, The composite design pattern.

1

Object Oriented ProgrammingLecture XII

Multithreading in Java, A few words about AWT and Swing, The composite design

pattern

Page 2: 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

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

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

Page 4: 1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing, The composite design 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

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

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

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

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

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

7

Dissecting the memory

Program

code

Static data

HeapThread stacks

shared data space

references

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

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();}}

}….

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

9

Counter1 output(class Counter1 continued.)

public static void main(String[] args) { new Counter1(0, 50, 20).start(); new Counter1(0, 50, 20).start(); }}

jabba% java Counter1T0: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

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

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 Threads are running now?

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

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();

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

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

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

13

Modes of ThreadsAlive

Blocked Runnable

Sleeping

Wait for targetto finish

Wait to benotified

Interrupted

Notinterrupted

New

Dead

interrupt()

sleep()

wait()

notify()

join()

Target finish

start()

run ()returns

interrupt()

yield()

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

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 **/

} }}

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

15

Counter2 output(class Counter2 continued.)

public static void main(String[] args) { new Counter2(0, 50, 20).start(); new Counter2(0, 50, 20).start(); }}

jabba% java Counter2T0: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

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

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(); }

}}

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

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?

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

18

Counter3 outputjabba% java Counter3T0: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,

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

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

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

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;

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

21

Avoiding data races

Thread 1:

lock(l);

x = x+1;

unlock(l);

Thread 2:

lock(l);

x = x+2;

unlock(l);

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

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

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

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; }

}}

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

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?

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

25

Atomicity in balancepublic 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

}}

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

26

Java.util.concurrent• Concurrent Data structures

– ArrayBlockingQueue<E>• For threadsafe bounded queues

– ConcurrentHashMap<K,V>• Threadsafe hashmap

– ConcurrentLinkedQueue<E> • 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

– ...

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

27

Java.util.concurrent.atomic

• Atomic Classes and wrappers– AtomicBoolean – AtomicInteger – AtomicIntegerArray – AtomicLong – AtomicReference – ...

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

28

A Few words about AWT and Swing

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

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)

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

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

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

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

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

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

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

33

Structure of the Composite pattern

Client Component

operation()

Leaf

operation()

add(Component)remove(Component)getChild(int)

Component

operation()add(Component)remove(Component)getChild(int)

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

34

LayoutManager

Container

BorderLayout

CardLayout

FlowLayout

GridLayout

LayoutManager

LayoutManager2

GridBagLayout

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

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)

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

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


Recommended