+ All Categories
Home > Documents > Object-Oriented Programming Threads

Object-Oriented Programming Threads

Date post: 23-Feb-2016
Category:
Upload: shirin
View: 35 times
Download: 0 times
Share this document with a friend
Description:
Object-Oriented Programming Threads. Kirk Scott. Threads. 29.1 Background 29.2 Example. 29.1 Background. What are Threads?. Before trying to explain what the term thread refers to in Java programming, it is helpful to review some background concepts. - PowerPoint PPT Presentation
61
Object-Oriented Programming Threads Kirk Scott 1
Transcript
Page 1: Object-Oriented Programming Threads

1

Object-Oriented ProgrammingThreads

Kirk Scott

Page 2: Object-Oriented Programming Threads

2

Threads

• 29.1 Background• 29.2 Example

Page 3: Object-Oriented Programming Threads

3

29.1 Background

Page 4: Object-Oriented Programming Threads

4

What are Threads?

• Before trying to explain what the term thread refers to in Java programming, it is helpful to review some background concepts.

• One of these concepts is the order of execution of instructions in a program.

• This should be familiar. • The other concept is concurrency, which may

not be.

Page 5: Object-Oriented Programming Threads

5

• A program consists of a structured set of instructions where the order they come in is meaningful.

• The program may contain ifs and loops, which mean that the instructions aren’t necessarily executed sequentially in the order that they appear in the program.

• However, the logic of the program dictates that for any given program run, the instructions are executed in a well-defined order.

Page 6: Object-Oriented Programming Threads

6

• Concurrency refers to the following idea. • In a modern computer with a modern

operating system, more than one active program may exist at the same time.

• These co-existing programs don’t run simultaneously.

• Only one program can run at a time.

Page 7: Object-Oriented Programming Threads

7

• However, the programs run concurrently. • This means that part of the sequence of

instructions from one program is run, then part of a sequence from another, and so on.

• It is not necessary for one program to run from beginning to end before the next one can start.

• The programs alternate execution, interleaving subsequences of their instructions.

Page 8: Object-Oriented Programming Threads

8

• In the scenario described above, two completely different programs may be running concurrently.

• It is also possible to have more than one separate execution sequence through the same program running concurrently.

• It’s “as if” there were two copies of the same program—but it’s not necessary to make a copy.

Page 9: Object-Oriented Programming Threads

9

• Two execution sequences can simply share the same program code, and the system keeps track of which instruction in the code each sequence is on at any given time.

• Separate execution sequences sharing the same code are known as threads.

Page 10: Object-Oriented Programming Threads

10

• This term is a metaphor. • The lines of code in a program are like the yarn

that runs crosswise through woven cloth (known as the weft or woof).

• The sequences of execution are like the threads that run lengthwise through the cloth (known as the warp).

• Separate paths through the lines of code/yarn can be traced by following more than one thread.

Page 11: Object-Oriented Programming Threads

11

Synchronization and Concurrency Control

• By definition, threads share program code. • Complexity arises when two different threads

also share access to common data, with the potential to both read and modify it concurrently.

• Dealing with this is known generically as concurrency control.

Page 12: Object-Oriented Programming Threads

12

• In Java it is dealt with using a concept known as synchronization and the key word synchronized.

• If threaded code has shared data and concurrency control is not implemented, the code is said not to be thread safe.

• The compiler can recognize this condition and generate warnings and error messages indicating it.

Page 13: Object-Oriented Programming Threads

13

• Threading is an advanced topic that is usually covered in an operating systems course.

• It is not covered completely here. • In particular, this section will not cover

concurrency control or its solutions. • This unit is designed only to introduce the

syntax for creating multiple threads in Java.

Page 14: Object-Oriented Programming Threads

14

• It is not necessary for threaded code to share resources, and the example code is designed to illustrate threading without shared resources.

• One part of the first programming assignment involves threading, but it does not require concurrency control.

• As long as you do not write code which shares resources, you can write simple threaded code without problems.

Page 15: Object-Oriented Programming Threads

15

Making Thread Instances

• Java has a class named Thread which makes it possible to write threaded code.

• Syntactically, there are two different ways of accomplishing this.

• Here is a brief review of the first:

Page 16: Object-Oriented Programming Threads

16

Extending the Thread Class

• 1. In an application, write a class that extends the system supplied Thread class.

• 2. Override the run() method in that class.• The run() method will contain the executable

thread code for your application• 3. Construct one or more instances of your

class.• 4. Call the start() method on the object(s).

Page 17: Object-Oriented Programming Threads

17

• 5. The objects of that class, and the code in the class definition, are threaded.

• The number of objects which are constructed and have the start() method called on them defines the number of concurrent threads which will run when the program is executed.

Page 18: Object-Oriented Programming Threads

18

• Notice that this is an example of a callback sequence

• The user program calls an inherited method that is not seen, and never directly calls the overridden method that is visible in the code.

Page 19: Object-Oriented Programming Threads

19

• The start() method allocates memory for and initializes a new thread in the Java system.

• It then calls the object’s run() method. • If the user code calls the run() method

directly, initialization does not occur.

Page 20: Object-Oriented Programming Threads

20

• The approach to implementing threading described above is straightforward and will work in many cases.

• Keep in mind that it is only possible for a given class to extend one other class.

• Java doesn’t support multiple inheritance.

Page 21: Object-Oriented Programming Threads

21

Creating Instances of the Thread Class

• If the class to be threaded is already a subclass of another class, extending the Thread class is not possible.

• For example, suppose you would like to write a threaded applet.

• The applet class will have to extend the JApplet class and it won’t be possible to also extend the Thread class.

Page 22: Object-Oriented Programming Threads

22

• Instead of multiple inheritance, Java supports interfaces, and it is also possible to implement threaded code by implementing the Runnable interface.

• Here is a brief review of this second approach to writing threaded code:

Page 23: Object-Oriented Programming Threads

23

• 1. In an application, write a class that implements the system supplied Runnable interface.

• 2. Implement the run() method specified by the interface in the class.

• Again, the run() method will contain the application specific thread logic

Page 24: Object-Oriented Programming Threads

24

• 3. Construct one or more instances of that class.

• Since only the run() method is specified in the interface, note that the interface alone does not provide all of the machinery necessary for constructing and starting threads.

Page 25: Object-Oriented Programming Threads

25

• 4. For each object of the given class, construct a thread by calling the constructor Thread() and passing it a reference to the object.

• 5. Call the start() method on the instances of the Thread class so created.

Page 26: Object-Oriented Programming Threads

26

• As usual, there is much more information on this topic in the Java API documentation of the Thread class and the Runnable interface.

• For what it’s worth, the Thread class itself implements the Runnable interface.

• This accounts for why the Thread class contains a run() method.

Page 27: Object-Oriented Programming Threads

27

• The Thread class also has more than one constructor, making it possible to construct threads for runnable objects that are passed in.

• The whole scheme falls apart if the programmer does not implement a run() method in the given class.

Page 28: Object-Oriented Programming Threads

28

• Note two points which may be obvious: • 1) The constructors for the runnable class

itself will be application dependent. • What they contain does not depend on the

constructor for the Thread class.

Page 29: Object-Oriented Programming Threads

29

• 2) In this whole discussion, the contents of the run() method have not been discussed.

• What the run() method does is entirely application dependent.

• The run() method contains the code which is to be run concurrently by the different threads.

Page 30: Object-Oriented Programming Threads

30

Which Approach is Better?

• Consider the general description of the meaning of inheritance

• A subclass is a kind of, or more specific kind of its superclass

• Observe that an application specific class that is threaded is not a kind of thread

• Its run method does something, and multiple threads may be executing through that method

Page 31: Object-Oriented Programming Threads

31

• So from a philosophical viewpoint, the first approach, of extending the Thread class is “wrong”

• However, in many cases it is the simpler approach, so the Java API developers provided it

• Constructing threads and passing in the objects is the more flexible and philosophically agreeable approach

• It is also marginally more complicated

Page 32: Object-Oriented Programming Threads

32

29.2 Example

Page 33: Object-Oriented Programming Threads

33

MiscThread

• This example shows how multiple subframes can be added to a running application where each subframe has its own thread of execution.

• Each of the subframes has two registers and the threads for the subframes continually swap the contents of the registers.

• Because multiple subframes will exhibit the same behavior at the same time, concurrent execution is made visually apparent.

Page 34: Object-Oriented Programming Threads

34

• The Thread class contains a static, void method named sleep()

• This is what the API has to say about it:• sleep(long millis)

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

• Putting a call to sleep() in the run() method for the example can slow the register swapping down enough that it is easy to see.

Page 35: Object-Oriented Programming Threads

35

• Three screenshots are shown on the following overheads.

• In the main frame there are File menu options to make a subframe or exit.

• In the subframes there are registers, and in the subframe menu there are File options to restart or close the subframe.

• The idea is that multiple subframes can be opened and each of these subframes will concurrently swap its register contents

Page 36: Object-Oriented Programming Threads

36

Page 37: Object-Oriented Programming Threads

37

Page 38: Object-Oriented Programming Threads

38

Page 39: Object-Oriented Programming Threads

39

• The UML diagram for the application follows. • The critical things to note are the following: • The MiscThreadFrame can have 0 or more

instances of the MiscThreadSubFrame and the MiscThreadSubFrame class implements the runnable interface.

• In other words, overall, the application may have many threads, each embodied in a separate subframe.

Page 40: Object-Oriented Programming Threads

40

MiscThread

MiscThreadFrame

JMenuBar

JMenu

JMenuItem JMenuItem

MakeSubFrameListener ExitListener

MiscThreadSubFrame

JMenuBarContentPane

JMenu

JMenuItem JMenuItem

RestartLisener CloseListener

MiscThreadPanel GridLayout

MiscThreadRegister JPanel JPanel

MiscThreadByte JTextField JLabel

TextFieldListener

«interface»Runnable

1

1

0..*

1

11

1

1

1 1

11

1

1

1

1

222

1

1

1 1

1

1

Page 41: Object-Oriented Programming Threads

41

• The code for the MiscThreadSubFrame class will be shown below.

• Here is the declaration of the threaded class in the MiscThread example:

• class MiscThreadSubFrame extends JFrame implements Runnable

• (It is declared this way without an access modifier simply because all of the classes for the example were stored in a single .java file.)

Page 42: Object-Oriented Programming Threads

42

• The key point is that the subframe class is implemented in a form that leads to threads.

• MiscThreadSubFrame implements the Runnable interface.

• It would not be possible for it to extend the Thread class because it already extends the JFrame class.

• The subframes contain various components just as in non-threaded frames.

Page 43: Object-Oriented Programming Threads

43

• Some of the components are graphical representations of elements of the application.

• Other components contain instructions implementing program logic.

• In particular, the run() method, required by the implementation of the Runnable interface, contains that code which is concurrently run by different threads of the subframe class.

Page 44: Object-Oriented Programming Threads

44

• In the run() method the contents of the registers belonging to the frame are swapped.

• Observe that each subframe has its own registers.

• Individual subframes do not share access to components of other subframes.

Page 45: Object-Oriented Programming Threads

45

• This means that even though the threads execute concurrently in the run() method, there are no potential concurrency problems and no need for concurrency control in the application.

• The code for the subframe class is shown beginning on the following overhead

Page 46: Object-Oriented Programming Threads

46

• class MiscThreadSubFrame extends JFrame implements Runnable

• {• private MiscThreadPanel myPanel;

• private final int FRAMEW = 250;• private final int FRAMEH = 250;

Page 47: Object-Oriented Programming Threads

47

• public MiscThreadSubFrame()• {• setTitle("MiscThread Frame");• setSize(FRAMEW, FRAMEH);•  • myPanel = new MiscThreadPanel();• Container contentPane = getContentPane();• contentPane.add(myPanel, "Center");• addWindowListener(new WindowCloser());

Page 48: Object-Oriented Programming Threads

48

• JMenuBar menuBar = new JMenuBar();• setJMenuBar(menuBar);•  • JMenu fileMenu = new JMenu("File");• menuBar.add(fileMenu);•  • JMenuItem restartItem = new JMenuItem("Restart");• fileMenu.add(restartItem);

Page 49: Object-Oriented Programming Threads

49

• RestartListener myRestartListener = new RestartListener();

• restartItem.addActionListener(myRestartListener);•  • JMenuItem closeItem = new JMenuItem("Close");• fileMenu.add(closeItem);•  • CloseListener myCloseListener = new CloseListener();• closeItem.addActionListener(myCloseListener);• }

Page 50: Object-Oriented Programming Threads

50

• /* Here is the run() method. This tells you that MiscThreadSubFrame is a threaded class. */

• public void run()• {• while(true)• {• try• {• Thread.sleep(100);• }• catch(InterruptedException e)• {• System.out.println("InterruptedException: " + e);• }• myPanel.getRegisterA().swapRegisterContents(myPanel.getRegisterB());• }• }

Page 51: Object-Oriented Programming Threads

51

• private class WindowCloser extends WindowAdapter• {• public void windowClosing(WindowEvent event)• {• dispose();• }• }

Page 52: Object-Oriented Programming Threads

52

• private class RestartListener implements ActionListener

• {• public void actionPerformed(ActionEvent

event)• {• Container contentPane = getContentPane();• contentPane.remove(myPanel);• myPanel = new MiscThreadPanel();• contentPane.add(myPanel, "Center");• setVisible(true);• }• }

Page 53: Object-Oriented Programming Threads

53

• private class CloseListener implements ActionListener

• {• public void actionPerformed(ActionEvent

event)• {• dispose();• }• }

Page 54: Object-Oriented Programming Threads

54

• Recall that you create instances of the MiscThreadSubFrame through a menu option in the class above it, MiscThreadFrame

• The code for the MakeSubFrameListener, which is implemented as an inner class of the MiscThreadFrame class, will be shown below.

Page 55: Object-Oriented Programming Threads

55

• By selecting the option in the menu which has this listener attached to it, new subframes/threads come into existence in the application.

• As noted above, the MiscThreadSubFrame class implements the Runnable interface rather than extending the Thread class.

Page 56: Object-Oriented Programming Threads

56

• As a result, the code in this listener uses the second approach described in the previous section for creating subframe threads.

• An instance of a subframe is created, and this is passed as a parameter to the Thread() constructor when the corresponding thread is created.

Page 57: Object-Oriented Programming Threads

57

• The code is written so that the new subframes do not appear in exactly the same location when they are created.

• They are offset diagonally so they don’t completely cover each other up.

• The declaration and initialization of the subFrameLocation are not shown in this code

• That happens at the top of the class

Page 58: Object-Oriented Programming Threads

58

• private class MakeSubFrameListener implements ActionListener• {• public void actionPerformed(ActionEvent event)• {• MiscThreadSubFrame mySubFrame = new MiscThreadSubFrame();• mySubFrame.setLocation(subFrameLocation, subFrameLocation);• if(subFrameLocation >= 500)• {• subFrameLocation = 50;• }• else• {• subFrameLocation += 50;• }• Thread myThread = new Thread(mySubFrame);• myThread.start();• mySubFrame.setVisible(true);• }• }

Page 59: Object-Oriented Programming Threads

59

• In summary, the example illustrates the following:

• An application class that implements the Runnable interface by implementing the run() method

• The creation of threads by passing application class objects to the Thread class constructor

Page 60: Object-Oriented Programming Threads

60

• Threads which do not share access to data, and therefore don’t have concurrency issues

• Threads with calls to sleep() making it possible to see concurrent execution in the graphical user interface

• And finally, the example illustrates the use of threads appropriate to the part in the first homework assignment dealing with threads

Page 61: Object-Oriented Programming Threads

61

The End


Recommended