CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 12: Nov 7-11, 2011 Aditya Mathur Department of Computer Science Purdue.

Slides:



Advertisements
Similar presentations
Written by: Dr. JJ Shepherd
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 13: Nov 14-18, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 10: Oct 24-28, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 8: Oct 10-14, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 4: September 12-16, 2011 Aditya Mathur/Tim Korb Department of Computer.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 13: Nov 15-19, 2010 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 16: Dec 6-10, 2010 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 9: Oct 17-21, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for the Final Lecture Dec 7, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 3: September 5-9, 2011 Aditya Mathur Department of Computer Science Purdue.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
CS 178: Programming with Multimedia Objects Aditya P. Mathur Professor of Computer Sciences Purdue University, West Lafayette Sept 9, 2004 Last update:
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
1 CS 177 Week 15 Recitation Slides Review. Announcements Final Exam on Sat. May 8th  PHY 112 from 8-10 AM Complete your online review of your classes.
GUI and Event-Driven Programming Recitation – 3/6/2009 CS 180 Department of Computer Science, Purdue University.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 11: Oct 31-Nov 4, 2011 Aditya Mathur Department of Computer Science Purdue.
Java and C++, The Difference An introduction Unit - 00.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 3: September 6-10, 2010 Aditya Mathur Department of Computer Science Purdue.
The Java Programming Language
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
CS 112 Department of Computer Science George Mason University CS 112 Department of Computer Science George Mason University Final Review Lecture 14.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 12: Nov 8-12, 2010 Aditya Mathur Department of Computer Science Purdue.
Classes and Objects CS177 Rec 10. Announcements Project 4 is posted ◦ Milestone due on Nov. 12. ◦ Final submission due on Nov. 19. Exam 2 on Nov. 4 ◦
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 11: Nov 1-5, 2010 Aditya Mathur Department of Computer Science Purdue University.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 14: Nov 21-25, 2011 Aditya Mathur Department of Computer Science Purdue.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 9: Oct 18-22, 2010 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 10: Oct 25-29, 2010 Aditya Mathur Department of Computer Science Purdue.
Written by: Dr. JJ Shepherd
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
OOP Basics Classes & Methods (c) IDMS/SQL News
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Chapter 9 Introduction to Arrays Fundamentals of Java.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Arrays Chapter 7.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
“Form Ever Follows Function” Louis Henri Sullivan
6 Chapter Functions.
CS Problem Solving and Object Oriented Programming Spring 2019
Review for Midterm 3.
CS Problem Solving and Object Oriented Programming Spring 2019
CS Problem Solving and Object Oriented Programming Spring 2019
FINAL EXAM Final Exam Tuesday, May 3: 1:00 - 3:00 PM (Phys 112)
CS Problem Solving and Object Oriented Programming Spring 2019
Presentation transcript:

CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 12: Nov 7-11, 2011 Aditya Mathur Department of Computer Science Purdue University West Lafayette, IN, USA This Week: 11/ Quiz 2.Review 3.Concurrent programming 4.Concurrent linear search 5.CHALLENGE PROBLEM 6.Concurrent bubble sort and merge

Readings and Exercises for Week 12 [Preparation for Exam 2] Readings: Chapters: 2, 3, 4, 5, 7, 8, 1, and 19 No questions on: Interfaces, inheritance, JOptionPane, images, sounds, applets Focus Exercises: Exam 2 Practice Problem Set [available via the course web site] ©Aditya Mathur. CS 180. Fall Week 12 File input (Scanner)/output (PrintWriter); Arrays: single and multidimensional; GUIs (with Action and Mouse Listeners; Grid and Border layouts).

Exam 2 When: Wednesday November 9, 2011; 8-10pm. Where: WTHR 200 Format:Open book [Any one book on Java] Two programming problems. Problem 1: Arrays/Files Problem 2: GUIs ©Aditya Mathur. CS 180. Fall Week 12 BRING YOUR ID!

Project 4 To type password so that characters do not show, use, but only if you wish to, JPasswordField pass=new JPasswordField () instead of JTextField(). ©Aditya Mathur. CS 180. Fall Week 12

Quiz ©Aditya Mathur. CS 180. Fall Week 12

1.Names of formal and actual parameters must be the same A True B. False ©Aditya Mathur. CS 180. Fall Week 12

2. Types of formal and actual parameters must be the same or convertible. A True B. False ©Aditya Mathur. CS 180. Fall Week 12

3. One of the following is incorrect. Which one. ? A.JPanel p=new JPanel(); B.JFrame f= new JFrame(“Is this OK?”); C.JPanel p= new JPanel(new GridLayout(3, 4)); D.JFrame f= new JFrame(new GridLayout(3, 4); ©Aditya Mathur. CS 180. Fall Week 12

4. One of the following is incorrect. Which one ? A.int [][] a=new int[][4]; B.int [][] a=new int[100][4]; C.int [][] a=new int[3][4]; D.int [][] a=new int[100][0]; ©Aditya Mathur. CS 180. Fall Week 12

5. Default layout for a JPanel is A.GridLayout B.FlowLayout C.BorderLayout D.BoxLayout ©Aditya Mathur. CS 180. Fall Week 12

6. When transferring actual parameters to a method the following is passed A.Value of the actual parameter B.Reference to the actual parameter C.None of the above ©Aditya Mathur. CS 180. Fall Week 12

7. A constructor is always required. A.True B.False ©Aditya Mathur. CS 180. Fall Week 12

8. There can be more than one constructor in a class definition. A.True B.False ©Aditya Mathur. CS 180. Fall Week 12

9. A non-static method in a class can directly call a static method in that class. A.True B.False ©Aditya Mathur. CS 180. Fall Week 12

10. A static method in a class can directly call a non-static method in that class. A.True B.False ©Aditya Mathur. CS 180. Fall Week 12

Review: Files ©Aditya Mathur. CS 180. Fall Week 12

File object File f; // declares an object of type File File f=new File (“data.txt”); // Create a File object String filename=“data.txt”; File f=new File (fileName); // Create a File object Full pathnames can be specified when creating a File object. ©Aditya Mathur. CS 180. Fall Week 12

File Input File f=new File (“data.txt”); // Create a File object Scanner inFile=new Scanner(f); // Creates a Scanner for data.txt Must be inside try-catch. boolean b= inFile.hasNext();// Checks if there is more data to be input String s=inFile.next(); // Read a string int num=inFile.nextInt(); // Read an int double num=inFile.nextDouble(); // Read a double ©Aditya Mathur. CS 180. Fall Week 12

File Output File f=new File (“data.txt”); // Create a File object PrintWriter outFile=new PrintWriter(f); // Creates a writer for data.txt Must be inside try-catch. outFile.print(d); // Write d in to the file; d may be any primitive type, // string, or even an arbitrary object. outFile.println(d); // Same as print() but terminates line. outFile.printf(format, d); // Same as print but formatted outFile.close();// Needed to ensure all data is flushed to the file. ©Aditya Mathur. CS 180. Fall Week 12

Review: Arrays ©Aditya Mathur. CS 180. Fall Week 12

Arrays of primitive types int [] a; // Declare an array int [] a=new int [n]; // Create an array long [][] x; // Declare an array long [][] x=new long [10][]; // Create an array long [][]x=new long [10][5]; // Create an array ©Aditya Mathur. CS 180. Fall Week 12

Array of primitive types: Visual int [] a=new int [3]; // Create an array ©Aditya Mathur. CS 180. Fall Week a a[0]=5; a

Arrays of objects JButton [] b; JButton [] b=new JButton[n]; ©Aditya Mathur. CS 180. Fall Week 12

Array of objects: Visual JButton [] b=new JButton[3]; ©Aditya Mathur. CS 180. Fall Week null b

Array of objects: Null pointer exception JButton [] b=new JButton[3]; ©Aditya Mathur. CS 180. Fall Week null b button[0].setText("Hello"); What happens if we do the following?

Array of objects: Creating an object JButton [] b=new JButton[3] b[0]=new JButton(“Hello”); ©Aditya Mathur. CS 180. Fall Week null b Hello

Array of objects: Modifying an object JButton [] b=new JButton[3] b[0]=new JButton(“Hello”); ©Aditya Mathur. CS 180. Fall Week 12 b[0].setText(”Hi!"); What happens if we do the following? null b Hi!

Array of objects: Another example Fruit [] f=new Fruit[3] ©Aditya Mathur. CS 180. Fall Week 12 f[0].setFruitColor(Color.Yellow); f[0].setPrice(3.99); null f f[0]=new Fruit(“Mango”); null f name: “Mango” color: price: name: “Mango” color: price: name: “Mango” color: Yellow price:3.99 name: “Mango” color: Yellow price:3.99

Review: Methods ©Aditya Mathur. CS 180. Fall Week 12

Method header ©Aditya Mathur. CS 180. Fall Week 12 Modifier public/ private/ none Modifier static/ none Return type NameParameters 0 or more public boolean find(int [] a, int x)

Method parameters ©Aditya Mathur. CS 180. Fall Week 12 public boolean find(int [] a, int x) Value parameter Reference parameter Value parameter: primitive types Reference parameter: objects

Value parameters ©Aditya Mathur. CS 180. Fall Week 12 public boolean find(int [] a, int x){ System.out.println(x); x++; } int y=15; int[] num={2, 3, 15, -29}; boolean found=find(num, y) System.out.println(found + ” “+ y); What is displayed? Value of actual parameter is passed

Reference parameters ©Aditya Mathur. CS 180. Fall Week 12 public boolean find(int [] a, int x){ System.out.println(a[1]); x++; a[1]++; } int y=15; int [] num={2, 3, 15, -29}; boolean found=find(num, y) System.out.println(found + ” “+ num[1]); What is displayed? Reference to actual parameter is passed

The main() method ©Aditya Mathur. CS 180. Fall Week 12 public static void main(String [] args){ } Is this value or a reference parameter? How can we pass parameters to the main() method?

Method parameter: summary ©Aditya Mathur. CS 180. Fall Week 12 A method may have zero or more parameters. Each parameter has a name. Each parameter must have a type All parameters are passed by value. For primitive types the value of the actual parameter is passed. For reference types a reference to the object is passed. Each method must have a return type. Each parameter becomes a local variable for the method. A constructor is a special method that has no return type.

Review: Class and instance variables ©Aditya Mathur. CS 180. Fall Week 12

Class and instance variables ©Aditya Mathur. CS 180. Fall Week 12 public class Home{ public static String measureUnit=“Square Feet”; public static String code=“Pub. L ”; private String address=“”; private int bedRooms=4; public Home(String a, int r){ address=a; bedRooms=r; } public int getBedrooms(){ return(bedRooms); } Class variables Instance variables

Class and instance variables ©Aditya Mathur. CS 180. Fall Week 12 Home h1=new Home(“1400 X Street”, 4); address=“1400 X Street” bedRooms=4 Home h2=new Home(“1500 Y Street”, 3); address=“1500 Y Street” bedRooms=3 System.out.println(Home.getBedRooms()); System.out.println(h2.getBedRooms()); System.out.println(h1.code); System.out.println(h2.code); System.out.println(h1.getBedRooms()); h1 h2 System.out.println(Home.code);

Class variables ©Aditya Mathur. CS 180. Fall Week 12 Declared using the static keyword. Not a part of the object, but part of the class in which they are declared. Accessible via the objects created from that class Declare a variable or a method as static only if does not depend on the object.

Instance variables ©Aditya Mathur. CS 180. Fall Week 12 Declared without using the static keyword Part of an object Accessible via the objects created from the parent class Declare a variable as an instance variable if its value depends on the object.

The main() method ©Aditya Mathur. CS 180. Fall Week 12 Is declared to be static Can it access instance variables in its parent class? What variables and methods in the parent class can the main method access?

Accessibility rules ©Aditya Mathur. CS 180. Fall Week 12 ModifierClassPackageSubclassWorld publicYYYY privateYNNN noneYYNN If a variable or an object declaration uses this modifier then can this variable or object be used inside ? Package: A collection of classes identified as a Java package. World: Collection of packages Y: Yes. N: No.

Review: Local and global variables ©Aditya Mathur. CS 180. Fall Week 12

Local variables ©Aditya Mathur. CS 180. Fall Week 12 public void test(int x){ int p, q; } x, p, q are local to method test. test is public and hence global and can be used in all classes. Variables and objects declared inside a method are local to that method.

Local variables: Use of public and private modifiers ©Aditya Mathur. CS 180. Fall Week 12 public void test(int x){ int p, q; public int z; } x, p, q are local to method test. test is public and hence global and can be used in all classes. Declarations inside a method cannot be preceded by public or private.

Global variables ©Aditya Mathur. CS 180. Fall Week 12 public class Toy{ public String name; private String owner; } name is global as it is declared to be public. Owner is local to this class Toy is global and can be used anywhere.

Local and global variables: Example public class X{ public JButton plus; public void doSomething(String c){ int z; for (int i=0; i<10; i++){ int p; } System.out.println(i, p); } // end of method }// end of class ©Aditya Mathur. CS 180. Fall Week 12 z, c can be use here i can be Used here i, p out of scope plus can be used here

Review: Inheritance ©Aditya Mathur. CS 180. Fall Week 12

Inheritance ©Aditya Mathur. CS 180. Fall Week 12 public class Fruit{ public String name; private String color=“Red”; int type; public void changeColor(String c){ Color=c; } public String getColor(){ return color; } public class Mango extends Fruit{ public String origin; public void harvest(){ } public String getOrigin(){ return color; } All methods and local variables/objects are available to Mango.

Inheritance: Another example ©Aditya Mathur. CS 180. Fall Week 12 public class Gui extends JFrame{ } All methods and local variables/objects of JFrame are available to Gui.

Review: GUI ©Aditya Mathur. CS 180. Fall Week 12

GUI: Widget/Methods ©Aditya Mathur. CS 180. Fall Week 12 JFrame JPanel JButton JTextField JMenuBar JMenu JMenuItem setSize() setVisible( ) setText() getText add()

GUI: Listeners/Methods ©Aditya Mathur. CS 180. Fall Week 12 ActionListener MenuListener KeyListener MouseListener getSource() addActionListener()

GUI: Interface ©Aditya Mathur. CS 180. Fall Week 12 A class implements an interface All methods in the interface must be implemented. ActionListener is an interface.

GUI: Abstract Class ©Aditya Mathur. CS 180. Fall Week 12 Similar to interface but may implement some methods thus avoiding the need to implement all methods. MouseAdapter is an abstract class.

Announcements ©Aditya Mathur. CS 180. Fall Week 11 No Feast With Faculty tonight due to Exam 2. Project 5 will be assigned this Friday, earlier than advertised, but the due date will not change. I will be out of the country next week. On Nov 14/16 Suleyman Centinas will solve problems related to concurrent programming. Please attend! Exam 2 TODAY! WTHR pm.

Concurrent Programming ©Aditya Mathur. CS 180. Fall Week 11

Dividing work into small segments ©Aditya Mathur. CS 180. Fall Week 11 class Instance variables Class variables Methods class Instance variables Class variables Methods class Instance variables Class variables Methods Program

Concurrency ©Aditya Mathur. CS 180. Fall Week 11 TT1T1 T2T2 TNTN.. T Main thread controls the distribution of work N threads executing concurrently to execute N tasks T 1, T 2 …T N. Distribute work Task T is divided into N simpler tasks and executed in parallel

Threads ©Aditya Mathur. CS 180. Fall Week 11 Thread is a class A thread is a sequence of computations that can run in parallel with other threads. One uses the Thread class to create a thread.

Problem ©Aditya Mathur. CS 180. Fall Week 11 Given doubles x and y and a boolean z, write a program to compute the following sin(x)/cos(y)+(x 2 +y 2 ); if z is true sin(x)/cos(y)+(x 2 - y 2 ); if z is false

Problem: Solution architecture ©Aditya Mathur. CS 180. Fall Week 11 T T1T1 T2T2 T T: Perform the given task T 1 : Compute a part of the expression T 2 : Compute a other part of the expression Combine the results of T 1 and T 2 How many threads?

Problem: Algorithm ©Aditya Mathur. CS 180. Fall Week 11 Thread A: Input: x and y Compute sin(x)/cos(y) Thread B: Input: x, y, z Compute x 2 +y 2 if z is true or x 2 -y 2 if z is false Thread C (control thread): Input: x, y, z; Create an object e1(Thread A ); Create can object e2(Thread B); Start e1; Start e2; Wait for e1 and e2 to complete; Get value computed by e1; Get value computed by e2; Add the two values and display the result;

Problem: Program ©Aditya Mathur. CS 180. Fall Week 11

Back to Concurrency ©Aditya Mathur. CS 180. Fall Week 12

Thread: What is it? ©Aditya Mathur. CS 180. Fall Week 12 A thread is a sequence of computation that can run in parallel with other threads. Every program has at least one thread of computation. Each thread is associated with an instance of the class Thread. A program with two or more threads is generally referred to as a multithreaded program. A multithreaded program is generally used to speed up the solution to a problem.

Thread: Typical lifecycle ©Aditya Mathur. CS 180. Fall Week 12 Define class that extends Thread. Create thread. Start thread. Wait for thread to terminate. Get results from thread. Use results from thread.

Thread: Defining a class ©Aditya Mathur. CS 180. Fall Week 12 Thread is a class. One way to create a new thread is to first define a class that extends the Thread class. public class Search extends Thread{ String [] x; // For use by a thread String s; // Another object for use by the thread int tID; // Thread ID if needed int start, end; // Start and end indices for search boolean found; // Computed by the thread }

Thread: The constructor ©Aditya Mathur. CS 180. Fall Week 12 A class that extends Thread generally has a constructor that is used to pass parameters to a thread as follows. public Search (String [] a, String s, int start, int end, int tID, ){ // Save parameters for use when the thread executes x=a; this.s=s; this.start=start; this.end=end; this.tID=tID }

Thread: The run() method ©Aditya Mathur. CS 180. Fall Week 12 Unlike the main() method, every thread object created from Thread must have a run() method. When a thread is started, its execution begins in the run() method and terminates when the run() method terminates

Thread: The run() method: Example ©Aditya Mathur. CS 180. Fall Week 12 public void run (){ // Must not have any parameters // Thread execution begins here. System.out.println(“Hi! I am thread “+tID); System.out.println(“Bye bye! See you!”); } The run() method does not take any parameters. The run() methods does not return any value.

Thread: Other methods ©Aditya Mathur. CS 180. Fall Week 12 A thread may have methods other than the run() method. Here is an example. public boolean getOutcome(){ return (found); // Return the outcome of search } Methods in a thread may be called during the execution of the run() method and even after the completion of the run() method.

Thread: run() method ©Aditya Mathur. CS 180. Fall Week 12 A run() method is like any other method except that it does not have any parameters or return type. A run() method may call any other method to complete its task.

Thread: Creation ©Aditya Mathur. CS 180. Fall Week 12 Create a thread object just as any other object. The following examples create two thread objects named one and two. Search one=new Search (a, s, start, end, 1); Search two=new Search (a, s, start, end, 2);

Thread: Start of execution ©Aditya Mathur. CS 180. Fall Week 12 Execution of a thread must be started using the start() method for that thread. Here are two examples for starting threads one and two. one.start(); // Starts the execution of thread object one two.start(); // Starts the execution of thread object two

Thread: Waiting for completion ©Aditya Mathur. CS 180. Fall Week 12 You may wait for a thread to complete execution using the join() method as follows. try{ one.join(); // Wait for thread one to complete two.join(); // Wait for thread one to complete catch(Exception e){} The try-catch block is needed. More on this later!

Thread: Extracting results ©Aditya Mathur. CS 180. Fall Week 12 You may extract the outcome of a thread’s execution in a variety of way. One way is to use an accessor method to do so. Here are examples. boolean f1=one.getOutcome(); // Get search outcome of thread one boolean f2=two.getOutcome(); // Get search outcome of thread two

Thread: Typical lifecycle [Review] ©Aditya Mathur. CS 180. Fall Week 12 Define class that extends Thread. Create thread. Start thread. Wait for thread to terminate. Get results from thread. Use results from thread.

Example: Concurrent search ©Aditya Mathur. CS 180. Fall Week 12

Problem 1 ©Aditya Mathur. CS 180. Fall Week 12 We are given a rather large array of strings. We wish to write a program that will determine, and display, whether or not a given string appears in the array. Given that the array is large, we are required to write a concurrent program that uses threads to solve the problem faster than it would if done sequentially.

Understanding the problem ©Aditya Mathur. CS 180. Fall Week 12 The problem is rather straightforward!

Search algorithm ©Aditya Mathur. CS 180. Fall Week 12 There are many search algorithms available. Given no information about how the array of strings is ordered, we will use a simple linear search algorithm. The given string will be compared with the first element of the array, then the next and so on until a match is found or all elements have been compared. If a match is found, the algorithm returns true, otherwise it returns false.

Concurrent search: Create threads ©Aditya Mathur. CS 180. Fall Week 12 a= q p r u s t Given array Create thread one Pass a, s and start and end indices to the constructor [start=0, end=2] Given string to be searched: s Create thread two Pass a, s and start and end indices to the constructor [start=3, end=5]

Concurrent search: Array partitioned ©Aditya Mathur. CS 180. Fall Week q p r u s t Thread one searches in this part of the array Thread two searches in this part of the array

Concurrent search: Next steps ©Aditya Mathur. CS 180. Fall Week 12 Start the threads; Wait for the threads to complete; Extract the search outcome of each thread; If any one of the threads found the string then the search was successful otherwise the search failed.

Live demo ©Aditya Mathur. CS 180. Fall Week 12

Challenge Problem ©Aditya Mathur. CS 180. Fall Week 12 You are given an array of integers. The integers in the array vary from 0 (inclusive) to 500 (inclusive). You are also given 3 bins. Write a concurrent program that distributes the integers in the array into the 3 bins such that bin 1 gets all integers less than 170, bin 2 gets all integers greater than 170 but less than 240, and bin 3 gets all integers greater than 240. Sort the bins in ascending order and display.

Challenge Problem: Example ©Aditya Mathur. CS 180. Fall Week 12 Given: array={3, 43, 129, 32, 400, 452, 5} Final contents of the three bins as displayed: bin 1={3, 5, 32, 43} bin 2={129} bin 3={400, 452}

Week 12: November 7-11, Hope you enjoyed this week! Questions? Contact your recitation instructor. Make full use of our office hours. ©Aditya Mathur. CS 180. Fall Week 12