28
University of Pittsburgh Comp uter Science 1 Week 4: Introduction Week 4: Introduction Last week we discussed Last week we discussed Why we want to use graphical Why we want to use graphical components components Event-driven programming Event-driven programming Program reacts to user's actions Program reacts to user's actions We have event generators We have event generators Components that trigger events Components that trigger events We have event handlers (listeners) We have event handlers (listeners) Subprograms execute in reaction to event Subprograms execute in reaction to event Different events can be distinguished Different events can be distinguished and are handled differently and are handled differently Ex. ActionEvent, MouseEvent, WindowEvent Ex. ActionEvent, MouseEvent, WindowEvent

University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

Embed Size (px)

Citation preview

Page 1: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

1

Week 4: IntroductionWeek 4: Introduction

• Last week we discussedLast week we discussed Why we want to use graphical Why we want to use graphical

componentscomponents

Event-driven programmingEvent-driven programming Program reacts to user's actionsProgram reacts to user's actions We have event generatorsWe have event generators

– Components that trigger eventsComponents that trigger events

We have event handlers (listeners)We have event handlers (listeners)– Subprograms execute in reaction to eventSubprograms execute in reaction to event

Different events can be distinguished and are Different events can be distinguished and are handled differentlyhandled differently– Ex. ActionEvent, MouseEvent, WindowEventEx. ActionEvent, MouseEvent, WindowEvent

Page 2: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

2

Week 4: IntroductionWeek 4: Introduction

Button example in JavaButton example in Java Variable is declaredVariable is declared Object is created and linked with listenerObject is created and linked with listener Code in listener subprogram handles eventCode in listener subprogram handles event

Mouse example in JavaMouse example in Java Different reactions to different types of Mouse Different reactions to different types of Mouse

EventsEvents– mousePressedmousePressed– mouseMovedmouseMoved– mouseDraggedmouseDragged

GUI programming can get complicated, but GUI programming can get complicated, but the the ideasideas are not that complex are not that complex Much easier to learn syntax/details once you Much easier to learn syntax/details once you

understand the ideasunderstand the ideas

Page 3: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

3

Week 4: MultitaskingWeek 4: Multitasking

• Often in life we have many things to Often in life we have many things to do (sometimes too many)do (sometimes too many) It would be nice if we had a clone!It would be nice if we had a clone! More realistically we have to divide our time!More realistically we have to divide our time!

Herb, make sure the Omega file is on my desk

Oh and have the treadmill set up please

And get that conference call ready as well

Page 4: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

4

Week 4: MultitaskingWeek 4: Multitasking

• How to divide our activities?How to divide our activities? People often do things People often do things SEQUENTIALLYSEQUENTIALLY

Do one thing until its finished, then the next, etc.Do one thing until its finished, then the next, etc.

1) Review Omega file until finished

2) Exercise on treadmill until tired

3) Talk on conference call until complete

Page 5: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

5

Week 4: MultitaskingWeek 4: Multitasking

• Sequential division is fine Sequential division is fine sometimes, but not alwayssometimes, but not always Doing things sequentially means that Doing things sequentially means that

some tasks are sitting around not getting some tasks are sitting around not getting done, possibly for quite a while done, possibly for quite a while Waiting in line at the supermarket or to buy Waiting in line at the supermarket or to buy

concert ticketsconcert tickets Cooking the spaghetti until it's done then Cooking the spaghetti until it's done then

cooking the sauce until it's done then cooking cooking the sauce until it's done then cooking the broccoli until it's donethe broccoli until it's done– Eating cold spaghetti Eating cold spaghetti

Page 6: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

6

Week 4: MultitaskingWeek 4: Multitasking

• Sometimes it is better if we can do Sometimes it is better if we can do more than one thing at the same timemore than one thing at the same time

Drive and talk on the cell phoneDrive and talk on the cell phone Eat and talk on the cell phoneEat and talk on the cell phone Walk the dog and talk on the cell phoneWalk the dog and talk on the cell phone Brush teeth and talk on the cell phoneBrush teeth and talk on the cell phone Eat, drive, walk the dog and brush teeth Eat, drive, walk the dog and brush teeth

while talking on the cell phonewhile talking on the cell phone

• Now we are doing things Now we are doing things in PARALLELin PARALLEL

Read the Omega file while exercising on the Read the Omega file while exercising on the treadmill and talking on the conference calltreadmill and talking on the conference call

Page 7: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

7

Week 4: MultitaskingWeek 4: Multitasking

• This doesn't always work so well eitherThis doesn't always work so well either Without clones, some things cannot be done Without clones, some things cannot be done

at the same timeat the same time

If the things require the same resources or resources If the things require the same resources or resources that are not both available at the same timethat are not both available at the same time

Ex. watching two TV programs at the same timeEx. watching two TV programs at the same time– Only one set of eyesOnly one set of eyes

Ex. riding a bicycle and water skiingEx. riding a bicycle and water skiing– Only one set of legsOnly one set of legs– Can't be on land and on the water at the same timeCan't be on land and on the water at the same time

Ex. attending L2L workshop and basking in the sunEx. attending L2L workshop and basking in the sun– L2L is indoorsL2L is indoors– Sun is outdoorsSun is outdoors

Page 8: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

8

Week 4: Time-SlicingWeek 4: Time-Slicing

• This problem is similar for the computerThis problem is similar for the computer Most computers only have one CPUMost computers only have one CPU

Often there are many things to do "at the Often there are many things to do "at the same time"same time"

Download a file from the internetDownload a file from the internet Run a Java applet in the Web BrowserRun a Java applet in the Web Browser

– Display graphicsDisplay graphics– Calculate locations of objectsCalculate locations of objects

Save a document onto a floppy diskSave a document onto a floppy disk

Computer handles this by Computer handles this by TIME-SLICINGTIME-SLICING Do a little of each job at a time, so it APPEARS Do a little of each job at a time, so it APPEARS

as if they are being done in parallelas if they are being done in parallel

Page 9: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

9

Week 4: Time-SlicingWeek 4: Time-Slicing

• How does time-slicing work?How does time-slicing work? Computer has a list of its jobs (or tasks, or Computer has a list of its jobs (or tasks, or

processes)processes)

Computer devotes a certain amount of time (a Computer devotes a certain amount of time (a sliceslice) to each job, in a round-robin fashion) to each job, in a round-robin fashion

Ex. a waiter in a restaurant goes around to all Ex. a waiter in a restaurant goes around to all of his customers every so oftenof his customers every so often– This way all of them are happyThis way all of them are happy

Computer follows the same ideaComputer follows the same idea

Page 10: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

10

Week 4: Time-SlicingWeek 4: Time-Slicing

•Without time-slicing, jobs are done in order, one after each other

•With time-slicing, jobs are interleaved, with each being done a little at a time

Page 11: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

11

Week 4: Programming Using Time-SlicingWeek 4: Programming Using Time-Slicing

• Modern GUI programs also need Modern GUI programs also need time-slicingtime-slicing Often a single program will have many things Often a single program will have many things

that need to be done "at the same time"that need to be done "at the same time"

Ex: Animations in which things move on the Ex: Animations in which things move on the screen, possibly at different ratesscreen, possibly at different rates

Ex: Multi-user internet games in which many Ex: Multi-user internet games in which many users log into the same server to playusers log into the same server to play

Ex: Chat programs in which users send Ex: Chat programs in which users send messages to each othermessages to each other

Page 12: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

12

Week 4: Java ThreadsWeek 4: Java Threads

• In Java, programming "in parallel" is In Java, programming "in parallel" is done using done using ThreadsThreads A Thread is (informally) an autonomous A Thread is (informally) an autonomous

flow of execution within a programflow of execution within a program Multiple threads (without any other restrictions) Multiple threads (without any other restrictions)

will execute independent of each otherwill execute independent of each other

The Java interpreter (together with the The Java interpreter (together with the operating system) perform the time-slicing operating system) perform the time-slicing that allow the Threads to all run "at the same that allow the Threads to all run "at the same time"time" Remember that in reality only one thread is actually Remember that in reality only one thread is actually

running at any given timerunning at any given time It just looks like they are all running at onceIt just looks like they are all running at once

Page 13: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

13

Week 4: Java ThreadsWeek 4: Java Threads

• How do threads work?How do threads work? Each thread will execute a subprogram Each thread will execute a subprogram

called run()called run() This could be the same or different for different This could be the same or different for different

threads in a programthreads in a program

As long as run() is executing, the thread is As long as run() is executing, the thread is "alive""alive"

Once run() completes for a thread, the Once run() completes for a thread, the thread is "dead"thread is "dead"

In our programs we can manipulate In our programs we can manipulate variables and conditions to determine variables and conditions to determine when and for how long a thread will runwhen and for how long a thread will run

Page 14: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

14

Week 4: Java ThreadsWeek 4: Java Threads

Let's look at a couple simple examplesLet's look at a couple simple examples Download Moving.java from the Web siteDownload Moving.java from the Web site

Compile and run itCompile and run it

Let's look at the codeLet's look at the code Note where Thread object is created and Note where Thread object is created and

start()ed runningstart()ed running Note the run() subprogramNote the run() subprogram

– In this case, it never stops until the program endsIn this case, it never stops until the program ends– Not always the caseNot always the case

Change some values and see the effectChange some values and see the effect Use Rectangle2D.Double for Ellipse2D.DoubleUse Rectangle2D.Double for Ellipse2D.Double Change deltaX and deltaY, startX and startYChange deltaX and deltaY, startX and startY Change sizeChange size

Page 15: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

15

Week 4: Java ThreadsWeek 4: Java Threads

Note that screen shows more of a "trail" than Note that screen shows more of a "trail" than of the object itselfof the object itself Window is not erased before new location is drawnWindow is not erased before new location is drawn

How can we fix this?How can we fix this? "Erase" previous copy of the object before "Erase" previous copy of the object before

drawing the new onedrawing the new one– We can do this by drawing the old copy in the We can do this by drawing the old copy in the

same color as the window background, then same color as the window background, then drawing the new copy in the correct colordrawing the new copy in the correct color

Download Moving2.javaDownload Moving2.java Compile and run itCompile and run it Look at the codeLook at the code

Page 16: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

16

Week 4: More ThreadsWeek 4: More Threads

• First two examples had only 1 threadFirst two examples had only 1 thread What if we want multiple threads in the same What if we want multiple threads in the same

program?program? Maybe many different things are moving or going Maybe many different things are moving or going

on in the same programon in the same program

Now we have to decide if the threads will Now we have to decide if the threads will be affecting each otherbe affecting each other Do they share any data or access the same Do they share any data or access the same

resources "at the same time".resources "at the same time".

If NOT, they can be totally independent, with If NOT, they can be totally independent, with their own data and never worry about each othertheir own data and never worry about each other

Page 17: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

17

Week 4: More ThreadsWeek 4: More Threads

• Let's look at an example of Let's look at an example of independent threadsindependent threads Notice in the previous program, a single Notice in the previous program, a single

thread controlled the movement of our objectthread controlled the movement of our object

What if we want more objects to move What if we want more objects to move around on the screen?around on the screen? If we want them to all move in the same way at If we want them to all move in the same way at

the same rate, we can still use just one threadthe same rate, we can still use just one thread But if we want them to be able to move at But if we want them to be able to move at

different speeds, it is better to use separate different speeds, it is better to use separate threads for each onethreads for each one

Download Bounce.java and run itDownload Bounce.java and run it

Page 18: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

18

Week 4: More ThreadsWeek 4: More Threads

Now look at the codeNow look at the code In main program we now have an array of In main program we now have an array of

NewBall objectsNewBall objects ActionListener in main program responds to ActionListener in main program responds to

button click by creating a new NewBall and button click by creating a new NewBall and adding it to the array adding it to the array

NewBall itself is a subclass (remember NewBall itself is a subclass (remember inheritance!) of Thread, so it can run() on its owninheritance!) of Thread, so it can run() on its own– Each NewBall is started as soon as it is createdEach NewBall is started as soon as it is created

Now the run() subprogram for each NewBall Now the run() subprogram for each NewBall will move that ball based on the random values will move that ball based on the random values set when that ball was createdset when that ball was created

A thread in the main class controls when the A thread in the main class controls when the balls are repaintedballs are repainted

Page 19: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

19

Week 4: More ThreadsWeek 4: More Threads

Note how threads stoppedNote how threads stopped– The variable that controls the loop is set to falseThe variable that controls the loop is set to false– Graceful terminationGraceful termination

Experiment with this code as wellExperiment with this code as well Run it and change some of the variablesRun it and change some of the variables

Page 20: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

20

Week 4: Concurrency IssuesWeek 4: Concurrency Issues

• Sometimes multiple threads will Sometimes multiple threads will interact with each other (sharing interact with each other (sharing data)data) In these situations, some issues must be In these situations, some issues must be

addressedaddressed Data ConsistencyData Consistency

– If two threads both act on the same If two threads both act on the same data, how do we ensure that the data data, how do we ensure that the data remains consistent remains consistent

– Ex: MAC machineEx: MAC machine

Page 21: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

21

Week 4: Concurrency IssuesWeek 4: Concurrency Issues

MAC MACHINE #1MAC MACHINE #1 MAC MACHINE #2MAC MACHINE #2Joe Schmoe checks Joe Schmoe checks

balance, says $200 are balance, says $200 are availableavailable

Jill Schmoe checks balance, Jill Schmoe checks balance, says $200 are availablesays $200 are available

Joe Schmoe withdraws Joe Schmoe withdraws $200$200

Jill Schmoe withdraws $200Jill Schmoe withdraws $200

The Schmoes’ balance is The Schmoes’ balance is updated to 0$updated to 0$

The Schmoes’ balance is The Schmoes’ balance is updated to -$200updated to -$200

Joe and Jill Schmoe get out of town as soon as they can!Joe and Jill Schmoe get out of town as soon as they can!

• We must keep our programs from having this problem

Page 22: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

22

Week 4: Concurrency IssuesWeek 4: Concurrency Issues

• How to prevent data inconsistency?How to prevent data inconsistency? We must make sure that important We must make sure that important

transactions are transactions are ATOMIC and EXCLUSIVEATOMIC and EXCLUSIVE A sequence of operations executes as if it is a A sequence of operations executes as if it is a

single operationsingle operation We guarantee that the thread executing these We guarantee that the thread executing these

operations will not be interrupted before they operations will not be interrupted before they are completedare completed

No other thread has access to the critical data No other thread has access to the critical data until the one executing is finisheduntil the one executing is finished

If we did this for the bank transaction, Jill If we did this for the bank transaction, Jill could not get in to check the balance until could not get in to check the balance until Joe was finished – and it would show $0Joe was finished – and it would show $0

Page 23: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

23

Week 4: Concurrency IssuesWeek 4: Concurrency Issues

In Java we enforce atomic and exclusive In Java we enforce atomic and exclusive access by using the access by using the MONITORMONITOR Critical data is placed within the monitorCritical data is placed within the monitor

Only one thread may access the monitor at a Only one thread may access the monitor at a timetime Java keyword Java keyword synchronizedsynchronized indicates monitor indicates monitor accessaccess

• Deadlock and StarvationDeadlock and Starvation Multiple threads share resources, such as Multiple threads share resources, such as

monitors (above), files, devices, etc.monitors (above), files, devices, etc.

Threads that do not have a resource but Threads that do not have a resource but that need it must wait until it is freethat need it must wait until it is free

Page 24: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

24

Week 4: Concurrency IssuesWeek 4: Concurrency Issues

If all threads are waiting for some If all threads are waiting for some resource or other, we have resource or other, we have DEADLOCKDEADLOCK

Thread B is using floppy disk, needs internet port

Thread A is using CD, needs floppy disk

Thread C on internet, needs monitor data

Thread D accessing monitor, needs CD

Page 25: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

25

Week 4: Concurrency IssuesWeek 4: Concurrency Issues

Sometimes resources are passed back and forth Sometimes resources are passed back and forth in such a way that most threads can execute, but in such a way that most threads can execute, but some never get the chance : some never get the chance : STARVATIONSTARVATION

Ex: 3 philosophers sitting around a table Ex: 3 philosophers sitting around a table want to eat spaghettiwant to eat spaghetti

There are 3 forks total, one between There are 3 forks total, one between each pair of philosopherseach pair of philosophers

A philosopher needs two forks to eatA philosopher needs two forks to eat

How to get the philosophers to all eat?How to get the philosophers to all eat?

Page 26: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

26

Week 4: Concurrency IssuesWeek 4: Concurrency Issues

If each philosopher grabs one fork, we have deadlock

If two philosophers team up, passing forks back and forth, the third will suffer from starvationWe want our threads to avoid this problem

Page 27: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

27

Week 4: Concurrency IssuesWeek 4: Concurrency Issues

• Avoiding deadlock and starvationAvoiding deadlock and starvation Programmer must anticipate resource Programmer must anticipate resource

needs and manage them carefullyneeds and manage them carefully

Threads must be carefully synchronizedThreads must be carefully synchronized

Page 28: University of Pittsburgh Computer Science 1 Week 4: Introduction Last week we discussedLast week we discussed èWhy we want to use graphical components

University of Pittsburgh Computer Science

28

Week 4: SummaryWeek 4: Summary

• Today we discussedToday we discussed Why programs sometimes need to do Why programs sometimes need to do

things “at the same time”things “at the same time”

How time-slicing is done using threads in How time-slicing is done using threads in JavaJava

How multiple threads can be used in the How multiple threads can be used in the same programsame program

Issues concerning threadsIssues concerning threads Data consistencyData consistency DeadlockDeadlock StarvationStarvation