Download presentation
Presentation is loading. Please wait.
Published byFranklin Shelton Modified over 8 years ago
1
Five-Minute Review 1.What are the three data structures realized in the Java Collections Framework? 2.What is hashing used for, how does it work? 3.What do iteractors do? 4.What are interactive programs? 5.What types of events do we distinguish? 1
2
We Want You for future InfProgOO ! Apply now to rvh@... [Wikimedia Commons] 2
3
Programming – Lecture 14 Looking Ahead (Chapter 14) Programming patterns, MVC Concurrency Race Conditions 3
4
Programming Patterns In 1994, Addison-Wesley published Design Patterns, a groundbreaking book that called attention to the fact that many programming problems are most easily solved by applying certain common software patterns. Although the patterns described in the book are typically implemented using classes and methods, each pattern tends to represent more of a general solution strategy for some class of problems and not a ready- made solution.
5
The Model/View/Controller Pattern Controller View Model The user interacts with a MVC-based user interface through the controller, which is the part of the system capable of accepting user commands. It is typically a collection of Swing interactors. The controller never updates the displayed data directly. It instead sends requests to the model, which keeps track of the state of the system but is separate from the user interface. When changes occur in the model, it sends messages to one or more views, which are responsible for updating the information that the user sees on the display. One of the most important patterns in terms of its applicability to user-interface design is the model/view/controller pattern, which is often abbreviated as MVC.
6
The HousePoints Program The HousePoints program described in section 14.4 uses the model/view/controller pattern to present two views of the house points assigned to the Hogwarts houses at the end of J. K. Rowling’s Harry Potter and the Philosopher’s Stone. The first appears as a bar graph, the second as a pie chart. In this example, the role of the controller is taken by the interactors at the bottom of the window. The controller sends messages to the model, which in turn updates both views. HousePoints Points Graph 312, 352, 426, 472 4, 352, 426, 47248, 352, 426, 472482, 352, 426, 472
7
HousePoints Points Graph 312, 352, 426, 472 4, 352, 426, 47248, 352, 426, 472482, 352, 426, 472 Model – View – Controller 7
8
Concurrency One of the initial design criteria for Java was that it be able to support concurrency, which is simply the ability to carry on several activities in parallel, even on computers that have only one processor. The classical approach to supporting concurrency is called multiprogramming, in which a computer with a single processor runs multiple programs by sharing that processor among each of the individual processes. The computer runs one process for a short period and then switches over to one of the other processes, cycling around the different tasks to ensure that they all get a fair share of processor time. Java supports concurrency at a lower level by allowing users to create new threads, which are independent activities that coexist when the same program and share access to the same memory space. As in multiprogramming, a multithreaded system shares the processor among the active threads.
9
A Simple Concurrent Application The TestAnimatedSquare program on the next slide offers a simple illustration of multithreaded programming. Each of the squares shown in the sample run below is an instance of the AnimatedSquare class, which implements the Runnable interface which allows it to support a thread. TestAnimatedSquare The run method for each square causes it to move in a random direction, which changes every 50 steps.
10
Concurrency TestAnimatedSquare 10
11
/** * This program tests the AnimatedSquare class by putting two squares * on the screen and having them move independently. */ public class TestAnimatedSquare extends GraphicsProgram { public void run() { double x1 = getWidth() / 3 - SIZE / 2; double x2 = 2 * getWidth() / 3 - SIZE / 2; double y = (getHeight() - SIZE) / 2; AnimatedSquare redSquare = new AnimatedSquare(SIZE); redSquare.setFilled(true); redSquare.setColor(Color.RED); add(redSquare, x1, y); AnimatedSquare greenSquare = new AnimatedSquare(SIZE); greenSquare.setFilled(true); greenSquare.setColor(Color.GREEN); add(greenSquare, x2, y); Thread redSquareThread = new Thread(redSquare); Thread greenSquareThread = new Thread(greenSquare); waitForClick(); redSquareThread.start(); greenSquareThread.start(); } /* Private constants */ private static final double SIZE = 75; } The TestAnimatedSquare Program
12
/** * This class creates an animated square that has its own thread of control. * Once started, the square moves in a random direction every time step. * After CHANGE_TIME time steps, the square picks a new random direction. */ public class AnimatedSquare extends GRect implements Runnable { /* Creates a new AnimatedSquare of the specified size */ public AnimatedSquare(double size) { super(size, size); } /* Runs when this object is started to animate the square */ public void run() { for (int t = 0; true; t++) { if (t % CHANGE_TIME == 0) { direction = rgen.nextDouble(0, 360); } movePolar(DELTA, direction); pause(PAUSE_TIME); } /* Private constants */ private static final double DELTA = 2; /* Pixels to move each cycle */ private static final int PAUSE_TIME = 20; /* Length of time step */ private static final int CHANGE_TIME = 50; /* Steps before changing direction */ /* Private instance variables */ private RandomGenerator rgen = RandomGenerator.getInstance(); private double direction; } The AnimatedSquare Class
13
public class TestAnimatedSquare extends GraphicsProgram { public void run() { double x1 = getWidth() / 3 - SIZE / 2; double x2 = 2 * getWidth() / 3 - SIZE / 2; double y = (getHeight() - SIZE) / 2; AnimatedSquare redSquare = new AnimatedSquare(SIZE); redSquare.setFilled(true); redSquare.setColor(Color.RED); add(redSquare, x1, y); AnimatedSquare greenSquare = new AnimatedSquare(SIZE); greenSquare.setFilled(true); greenSquare.setColor(Color.GREEN); add(greenSquare, x2, y); Thread redSquareThread = new Thread(redSquare); Thread greenSquareThread = new Thread(greenSquare); waitForClick(); redSquareThread.start(); greenSquareThread.start(); } private static final double SIZE = 75; } 13
14
public class AnimatedSquare extends GRect implements Runnable { public AnimatedSquare(double size) { super(size, size); } public void run() { for (int t = 0; true; t++) { if (t % CHANGE_TIME == 0) { direction = rgen.nextDouble(0, 360); } movePolar(DELTA, direction); pause(PAUSE_TIME); } } private static final double DELTA = 2; private static final int PAUSE_TIME = 20; private static final int CHANGE_TIME = 50; private RandomGenerator rgen = RandomGenerator.getInstance(); private double direction; } 14
15
Race Conditions – Graphically 15
16
public class RectRace extends GraphicsProgram implements ComponentListener { // Enable listening to component resizing public void init() { addComponentListener(this); } // Whenever we get resized, start the painting threads public void componentResized(ComponentEvent e) { RectPaint paintRed = new RectPaint(Color.RED); RectPaint paintBlack = new RectPaint(Color.BLACK); Thread threadRed = new Thread(paintRed); Thread threadBlack = new Thread(paintBlack); threadRed.start(); threadBlack.start(); } 16
17
// Repaint the canvas in given color // Make this "synchronized" for consistent canvas private void repaint(Color color) { int width = getWidth(); int height = getHeight(); for (int y = 0; y < height; y += PIX) { for (int x = 0; x < width; x += PIX) { GRect pixel = new GRect(PIX, PIX); pixel.setColor(color); pixel.setFilled(true); add(pixel, x, y); } } } private static final int PIX = 5; // Size of pixel 17
18
// The repainting thread class class RectPaint implements Runnable { RectPaint(Color color) { this.color = color; } public void run() { repaint(color); } private Color color; } 18
19
Race Conditions – With Data 19
20
public class DataRace extends ConsoleProgram { public void run() { while (true) { readLine("Hit enter for another run: "); long start = System.nanoTime(); shared = 0; runThreads(); long time = System.nanoTime() - start; println("shared = " + shared + ", delta = " + delta + ", after " + time / 1000 / 1e3 + " msecs"); } } 20
21
private void runThreads() { Adder incr = new Adder("Incrementer", 1); Adder decr = new Adder("Decrementer", -1); Thread incrThread = new Thread(incr); Thread decrThread = new Thread(decr); decrThread.start(); incrThread.start(); try { incrThread.join(); decrThread.join(); } catch (InterruptedException e) { throw new ErrorException(e); } } 21
22
private void addDelta(int d) { delta = d; shared += delta; } // Ivars of DataRace private int shared; private int delta; 22
23
class Adder implements Runnable { public Adder(String name, int threadDelta) { this.name = name; this.threadDelta = threadDelta; } public void run() { for (int i = 0; i < ITER_CNT; i++) { addDelta(threadDelta); } println(name + " has finished."); } private String name; private int threadDelta; static private final int ITER_CNT = 1000000; } } 23
24
Periodic Tasks public BallModel() {... timer = new Timer(BALL_CYCLE); timer.reset(); } public void run() { while (true) { move(); timer.pause(); } } private Timer timer; private static final int BALL_CYCLE = 25; 24
25
public class Timer { public Timer(double period) { this.period = period; reset(); } public void reset() { nanoTime = System.nanoTime(); delay = period; }
26
public void pause() { double preNanoTime = nanoTime; nanoTime = System.nanoTime(); double cycleTime = (nanoTime - preNanoTime) / 1e6; double rawDelayAdjustment = period - cycleTime; double delayAdjustment = DAMPENING * rawDelayAdjustment; delay += delayAdjustment; if (delay > 0) { JTFTools.pause(delay); } } 26
27
private double nanoTime; private double period; private double delay; private static final double DAMPENING = 0.1; } 27
28
Summary I Good software engineering makes use of patterns, as proposed by Gang of Four One important pattern is Model-View-Controller (MVC) Concurrency is an powerful yet tricky programming concept The Java event model already entails concurrency Java also supports concurrency with user-level threads A thread can be constructed with a runnable object, which is constructed from a class that implements the Runnable interface 28
29
The runnable object needs a run method After creating a thread with a Thread constructor, we must still explicitly start it We can wait for completion of a thread with join The concurrent use of shared may result in write- write races or write-read races Some, but not all, race conditions can be avoided by acquiring a monitor lock (or simply lock) on an object One way to get a lock on an object is to call a synchronized method of it 29 Summary II
30
[flickr / Creative Commons 2.0] Remember? Kieler Brauerei After exam: March 21, 5pm 30
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.