Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object-Oriented Programming Threads

Similar presentations


Presentation on theme: "Object-Oriented Programming Threads"— Presentation transcript:

1 Object-Oriented Programming Threads
Kirk Scott

2

3

4 Threads 1 Background 2 The Two Approaches in Syntax 3 Example
4 Some Rock Bottom Java Swing Stuff

5 1 Background

6 What are Threads? A program consists of a 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.

7 However, the logic of the program dictates that for any given program run, the instructions are executed in a well-defined order. A very simple machine may have a single processor which can only be running one sequence of instructions at a time

8 In a modern machine there may be multiple cores, which means that more than one sequence of instructions can be running at the same time In order to understand threads, it’s necessary to restrict your attention to a single processor or a single core

9 Any single processor or core can only run one sequence of instructions at a time
In simple terms, a thread is a single sequence of instructions that is running on such a one-at-a-time processing unit

10 In fact, a single processing unit can run more than one sequence of instructions at a time—
Just not simultaneously The sequences of instructions are scheduled The processor runs a few instructions from one sequence, then the other, then back again

11 This is referred to as concurrency
It is not necessary for one sequence to run from beginning to end before the next one can start The sequences alternate execution, interleaving subsequences of their instructions.

12 In the scenario as described above, two completely different programs could be running concurrently on the same processor It is also possible to have more than one separate execution path through the same sequence of instructions running concurrently. It’s “as if” there were two copies of the same program

13 However, there aren’t literally two copies of the code.
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.

14 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 (the weft) can be traced by following more than one thread (the warp).

15 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.

16 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.

17 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.

18 It is not necessary for threaded code to share resources, and the example code is designed to illustrate threading without shared resources. As long as you do not write code which shares resources, you can write simple threaded code without problems. You don’t have to synchronize your code

19 2 The Two Approaches in Syntax
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:

20 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).

21 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.

22 Notice that this is an example of a callback sequence
The user program calls an inherited method that is not seen, start(), and never directly calls the overridden method that is visible in the code, run().

23 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.

24 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.

25 Implementing the Runnable Interface
If the class to be threaded is already a subclass of another class, extending the Thread class is not possible. Instead of multiple inheritance, Java supports interfaces, and it is also possible to implement threaded code by implementing the Runnable interface.

26 This is the second approach to writing threaded code:
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. The run() method will contain the application specific thread logic

27 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.

28 4. For each object of the given class, construct a thread by calling the Thread class constructor, Thread(), and passing it a reference to the runnable object. 5. Call the start() method on the instances of the Thread class so created.

29 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.

30 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 class passed in as a construction parameter to a Thread.

31 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.

32 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.

33 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

34 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 by passing in runnable objects is the more flexible and philosophically agreeable approach It is also marginally more complicated

35 3 Example

36 It is possible to write a very simple example that illustrates the function of threads
The example includes a class named IdiotThread, which implements the Runnable interface It also includes a class named IllustrateThreads, which has a main() method and creates and runs some threads

37 The example code includes one other feature which often proves useful when running threads which the user wants to look at when trying to understand what’s going on It includes a call to the static method sleep(), which causes whichever thread is currently executing to temporarily stop

38 The parameter for sleep is given in milliseconds
By choosing a suitable value, it’s possible to bring things being printed out, for example, down to a human readable speed

39 The example code is shown on the following overheads
It is not commented Hopefully, the discussion of threads in the previous section plus the explanation of sleep() were clear and the code is self-explanatory

40 public class IdiotThread implements Runnable
{ private String whoAmI; public IdiotThread(String whoAmIIn) whoAmI = whoAmIIn; } public void run() while(true) System.out.println(whoAmI); try Thread.sleep(1000); catch(InterruptedException e) System.out.println("Sleeping problem in load().");

41 public class IllustrateThreads
{ public static void main(String[] args) IdiotThread myIdiotThread1 = new IdiotThread("I am thread 1"); Thread myThread1 = new Thread(myIdiotThread1); IdiotThread myIdiotThread2 = new IdiotThread("I am thread 2"); Thread myThread2 = new Thread(myIdiotThread2); myThread1.start(); myThread2.start(); }

42 If you compile the classes and execute IllustrateThreads, in the Java console you will see this kind of output, switching at random intervals between the first and second threads: I am thread 1 I am thread 2

43 This output graphically illustrates the Java virtual machine scheduler alternating execution between the two threads If you are running in a simple development environment you can kill these infinitely looped threads by simply closing the project files

44 The example code 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 Threads which do not share access to data, and therefore don’t have concurrency issues

45 4 Some Rock Bottom Java Swing Stuff
Java Swing is outdated, but it’s still a quick and dirty way to create a simple graphical user interface for a Java application Two examples are given in this section which may be adapted for use when working the homework assignment that uses threads

46 The outline of the structure of the application is as follows:
The application has a JFrame This contains a JEditorPane This contains a ScrollPane Inside that, the contents of a Web address are loaded

47 The first example is straightforward
If you test the example, you will see that although you can capture the contents of a Web page in this way, they don’t display well For our purposes, the bad display is unimportant All we want is to know that our code actually went out to the Internet and got something

48 import javax.swing.JEditorPane; import javax.swing.JFrame;
import java.net.URL; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JScrollPane; import java.io.IOException; public class FramePaneWebExample { public static void main(String[] args) JFrame myFrame = new JFrame(); JEditorPane myEditorPane = new JEditorPane(); try myEditorPane.setPage(new URL(" } catch(IOException e1) System.out.println("I/O problem."); myFrame.add(new JScrollPane(myEditorPane)); myFrame.setSize(1000, 1000); myFrame.setVisible(true);

49 The next example is slightly more complicated
It accomplishes essentially the same thing, but uses a rather convoluted structure The reason for showing this example is that this kind of structure will show up when implementing proxy

50 The various things the example illustrates include:
You can make a subclass of a system class, giving it additional instance variables You can write constructors which handle those instance variables You can write entirely new methods for the subclass

51 Also, you can change the contents of Swing components like panes, and so on
When you do change the contents, to cause the update to be displayed you have to call the repaint() method In this example, a reference to the application’s JFrame is passed around so that it is available to have repaint() called on it when the content changes

52 import javax.swing.JFrame;
import javax.swing.JScrollPane; public class TestEditorPaneSubclass { public static void main(String[] args) JFrame myFrame = new JFrame(); MyEditorPaneSubclass myPane = new MyEditorPaneSubclass(" myFrame); myFrame.add(new JScrollPane(myPane)); myFrame.setSize(1000, 1000); myFrame.setVisible(true); myPane.doDisplay(); }

53 import java.net.URL; import javax.swing.JEditorPane; import java.io.IOException; import javax.swing.JFrame; public class MyEditorPaneSubclass extends JEditorPane { private String URLPath; private JFrame myFrameReference; public MyEditorPaneSubclass(String URLPathIn, JFrame myFrameIn) URLPath = URLPathIn; myFrameReference = myFrameIn; } public void doDisplay() try this.setPage(new URL(URLPath)); myFrameReference.repaint(); catch(IOException e1) System.out.println("I/O problem 2.");

54 Like with many examples, it seems unnecessarily complicated because it is unnecessarily complicated in order to accomplish what it actually does However, it gives you some idea of the kind of structure you will need to use in a more complex situation

55 The End


Download ppt "Object-Oriented Programming Threads"

Similar presentations


Ads by Google