Object-Oriented Programming Threads

Slides:



Advertisements
Similar presentations
Introduction to Java.
Advertisements

 It is possible to declare names for object references and not assign object references to them.  Such names literally refer to nothing at all.  It.
Java.  Java is an object-oriented programming language.  Java is important to us because Android programming uses Java.  However, Java is much more.
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Lecture 17: Animation Yoni Fridman 7/27/01 7/27/01.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
CSCI-383 Object-Oriented Programming & Design Lecture 15.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
4.1 Instance Variables, Constructors, and Methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Unit 4 Prototype Summary prepared by Kirk Scott 1.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
CS 320 Assignment 1 Rewriting the MISC Osystem class to support loading machine language programs at addresses other than 0 1.
Object-Oriented Programming (Java), Unit 29 Kirk Scott 1.
1 Web Based Programming Section 8 James King 12 August 2003.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Object-Oriented Programming (Java), Unit 29 Kirk Scott 1.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
© Wang Bin 2004 Java Threads. © Wang Bin 2004 In this lesson, you will learn to: u Define the concepts of threads and multithreading  Identify the functions.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
CSCI 383 Object-Oriented Programming & Design Lecture 15 Martin van Bommel.
Java Thread Programming
Multithreading The objectives of this chapter are:
Summary prepared by Kirk Scott
HW 1 Kirk Scott.
Concepts of Object Oriented Programming
Multi Threading.
Distributed Shared Memory
Threads and Multithreading
CSE 501N Fall ‘09 21: Introduction to Multithreading
Android 11: The Calculator Assignment
Unified Modeling Language
Text by: Lambert and Osborne
Multithreaded Programming in Java
Java Unit 11: Inheritance I
Threads and Multithreading
Threads and Multithreading
Multithreading.
What is Concurrent Programming?
Threads and Multithreading
Threads and Multithreading
Threads Chapter 4.
Java Inheritance.
Multithreaded Programming
What is Concurrent Programming?
Threads and Multithreading
COP 3330 Object-oriented Programming in C++
ECE 352 Digital System Fundamentals
Threads and Multithreading
Threads and Multithreading
Multithreading in java.
Threads and Multithreading
Threads and Multithreading
Review of Previous Lesson
Threads and Multithreading
Threads.
Programming with Shared Memory Specifying parallelism
CMSC 202 Exceptions.
Multithreading The objectives of this chapter are:
CMSC 202 Threads.
Threads and concurrency / Safety
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Object-Oriented Programming Threads Kirk Scott

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

1 Background

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.

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

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

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

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

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.

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

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.

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

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.

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.

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.

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

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:

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

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.

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

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.

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.

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.

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

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.

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.

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.

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.

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.

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.

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

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

3 Example

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

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

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

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

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

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

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

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

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

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

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

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

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("http://ic.payap.ac.th/")); } catch(IOException e1) System.out.println("I/O problem."); myFrame.add(new JScrollPane(myEditorPane)); myFrame.setSize(1000, 1000); myFrame.setVisible(true);

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

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

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

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("http://ic.payap.ac.th/", myFrame); myFrame.add(new JScrollPane(myPane)); myFrame.setSize(1000, 1000); myFrame.setVisible(true); myPane.doDisplay(); }

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.");

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

The End