1 / 105

Java Threads and Java Collections

Java Threads and Java Collections. Four kinds of thread programming Thread Applications A GUI application A server application. Collections with examples. Four kinds of thread programming. 1) Unrelated threads 2) Related but unsynchronized threads 3) Mutually-exclusive threads

rickreeves
Télécharger la présentation

Java Threads and Java Collections

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Threads and Java Collections • Four kinds of thread programming • Thread Applications • A GUI application • A server application • Collections with examples 95-713

  2. Four kinds of thread programming 1) Unrelated threads 2) Related but unsynchronized threads 3) Mutually-exclusive threads 4) Communicating mutually-exclusive threads We will look at only the first two kinds. 95-713

  3. Unrelated threads class Coffee extends Thread { Coffee(String name) { super(name); } public void run() { for(int n = 1; n <= 3; n++) { System.out.println("I like coffee"); yield(); System.out.println(this.getName()); yield(); } } } 95-713

  4. class Tea extends Thread { Tea(String name) { super(name); } public void run() { for(int n = 1; n <= 3; n++) { System.out.println("I like tea"); yield(); System.out.println(this.getName()); yield(); } } } 95-713

  5. public class Drinks { public static void main(String args[]) { System.out.println("I am main"); Coffee t1 = new Coffee("Wawa Coffee"); Tea t2 = new Tea(“Sleepy Time Tea"); t1.start(); t2.start(); System.out.println("Main is done"); } } 95-713

  6. Output I am main Main is done I like coffee I like tea Wawa Coffee Sleepy Time Tea I like coffee I like tea Wawa Coffee Sleepy Time Tea I like coffee I like tea Wawa Coffee Sleepy Time Tea Main finishes right away Threads are sharing time This program has three threads. 95-713

  7. Unrelated Threads Part II • Using sleep() in unrelated threads • The call sleep(millis) puts the currently executing thread to • sleep for at least the specified number of milliseconds. "At • least“ means there is no guarantee the thread will wake up • in exactly the specified time. Other thread scheduling can • interfere. 95-713

  8. class Coffee extends Thread { Coffee(String name) { super(name); } public void run() { for(int n = 1; n <= 3; n++) { System.out.println("I like coffee"); try { sleep(1000); // 1 second } catch(InterruptedException e) {} System.out.println(this.getName()); } } } 95-713

  9. class Tea extends Thread { Tea(String name) { super(name); } public void run() { for(int n = 1; n <= 5; n++) { System.out.println("I like tea"); System.out.println(getName()); } } } 95-713

  10. public class Drinks2 { public static void main(String args[]) { System.out.println("I am main"); Coffee t1 = new Coffee("Wawa Coffee"); Tea t2 = new Tea("China Tea"); t1.start(); t2.start(); System.out.println("Main is done"); } } 95-713

  11. I am main Main is done I like coffee I like tea China Tea I like tea China Tea I like tea China Tea I like tea China Tea I like tea China Tea Wawa Coffee I like coffee Wawa Coffee I like coffee Wawa Coffee After “I like coffee”, the coffee thread goes to sleep and the tea thread gets to finish and die. 1 second pausing after each “I like coffee” 95-713

  12. Yield() and Sleep() • Yield() may have no effect on some implementations. • The thread scheduler might make no effort toward fairness. • The yielding thread may be picked again even though other threads want a turn. • It is a good idea to call sleep() instead. 95-713

  13. An Example Without Threads Black ball bounces for awhile and then stops. If you then click start, a new ball bounces for awhile and then stops. Close only works between balls. If the ball is moving and you click close, the close message is queued. 95-713

  14. // From Cay Horstmann Core Java 2 Advanced import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Bounce { public static void main(String[] args) { JFrame frame = new BounceFrame(); frame.show(); } } 95-713

  15. class BounceFrame extends JFrame { public BounceFrame() { setSize(300, 200); setTitle("Bounce"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); 95-713

  16. Container contentPane = getContentPane(); canvas = new JPanel(); contentPane.add(canvas, "Center"); JPanel p = new JPanel(); addButton(p, "Start", new ActionListener() { public void actionPerformed(ActionEvent evt) { Ball b = new Ball(canvas); b.bounce(); } }); 95-713

  17. addButton(p, "Close", new ActionListener() { public void actionPerformed(ActionEvent evt) { System.exit(0); } }); contentPane.add(p, "South"); } public void addButton(Container c, String title, ActionListener a) { JButton b = new JButton(title); c.add(b); b.addActionListener(a); } private JPanel canvas; } 95-713

  18. class Ball { public Ball(JPanel b) { box = b; } public void draw() { Graphics g = box.getGraphics(); g.fillOval(x, y, XSIZE, YSIZE); g.dispose(); } 95-713

  19. public void move() { Graphics g = box.getGraphics(); g.setXORMode(box.getBackground()); g.fillOval(x, y, XSIZE, YSIZE); x += dx; y += dy; Dimension d = box.getSize(); if (x < 0) { x = 0; dx = -dx; } if (x + XSIZE >= d.width) { x = d.width - XSIZE; dx = -dx; } if (y < 0) { y = 0; dy = -dy; } if (y + YSIZE >= d.height) { y = d.height - YSIZE; dy = -dy; } g.fillOval(x, y, XSIZE, YSIZE); g.dispose(); } 95-713

  20. public void bounce() { draw(); for (int i = 1; i <= 1000; i++) { move(); try { Thread.sleep(5); } catch(InterruptedException e) {} } } private JPanel box; private static final int XSIZE = 10; private static final int YSIZE = 10; private int x = 0; private int y = 0; private int dx = 2; private int dy = 2; } 95-713

  21. Bouncing With Threads The close button works in an instant. Each time the start button is clicked a new ball appears. The screen above shows four fast moving bouncing balls. 95-713

  22. We use start() rather than bounce() on the ball object… addButton(p, "Start", new ActionListener() { public void actionPerformed(ActionEvent evt) { Ball b = new Ball(canvas); b.start(); } }); 95-713

  23. …and have the Ball class extend Thread and implement run() rather than bounce(). class Ball extends Thread : public void run() { try { draw(); for (int i = 1; i <= 1000; i++) { move(); sleep(5); } } catch(InterruptedException e) {} } 95-713

  24. Ping Pong • Adapted from "The Java Programming Language", Arnold • and Gosling • After a thread is created, you can configure it – set its name, • its initial priority, and so on. • The start() method spawns a new thread of control based on • the data in the thread object and then returns. Now, the • Java virtual machine invokes the new thread's run method, • making the thread active. • When a thread's run method returns, the thread has exited. • The thread may be manipulated with a number of methods, • including the interrupt() method as shown in this example. 95-713

  25. public class PingPong extends Thread { private String word; private int delay; public PingPong(String whatToSay, int delayTime) { word = whatToSay; delay = delayTime; } 95-713

  26. public void run() { try { for(;;) { System.out.println(word+" "); sleep(delay); } } catch (InterruptedException e) { System.out.println("Interrupted!!!!!"); return; } } 95-713

  27. public static void main(String args[]) { PingPong t1 = new PingPong("\tping",33); t1.start(); PingPong t2 = new PingPong("Pong",100); t2.start(); try { Thread.sleep(5000); } catch(InterruptedException e) { // will not be printed System.out.println("Good morning"); return; } 95-713

  28. Thread myThread = Thread.currentThread(); for (int t = 1 ; t <= 10; t++) System.out.println("In Main..." + myThread.getName()); t1.interrupt(); } } 95-713

  29. C:\McCarthy\threads\PingPong>java PingPong ping Pong ping ping ping Pong ping ping ping Pong ping ping ping : : Main is asleep. For 5 seconds ping and pong take turns sleeping and running 95-713

  30. Pong ping ping ping Pong In Main...main In Main...main In Main...main In Main...main In Main...main In Main...main In Main...main In Main...main In Main...main In Main...main Interrupted!!!!! Pong Pong Pong Pong Pong : Main wakes up Main interrupts Ping and ping dies. “Pongs” forever or until until ctrl-c 95-713

  31. A Thread Application --A Simple Web Server • Responds by sending the same file on each hit • Creates a new thread on each hit 95-713

  32. // A simple web server // Responds with the same file on each hit import java.net.*; import java.io.*; import java.util.*; public class OneFile extends Thread { static String theData = ""; static String contentType; static int contentLength; Socket theConnection; 95-713

  33. // construct each OneFile object with an existing socket public OneFile(Socket s) { theConnection = s; } // run the following code on each object public void run() { try { // get a PrintStream attached to this socket PrintStream os = new PrintStream( theConnection.getOutputStream()); // get a DataInputStream attached to this socket DataInputStream is = new DataInputStream( theConnection.getInputStream()); // read a line from the socket String request = is.readLine(); 95-713

  34. // HTTP/1.0 and later send a MIME header if(request.indexOf("HTTP/") != -1) { // we need to read the rest of the MIME header while(true) { String thisLine = is.readLine(); if(thisLine.trim().equals("")) break; } // respond to the client os.print("HTTP/1.0 200 OK\r\n"); // send the date Date now = new Date(); os.print("Date: " + now + "\r\n"); // send our name os.print("Server: OneFile 1.0\r\n"); 95-713

  35. // send the contentLength os.print("Content-length: " + theData.length() + "\r\n"); // send the content type os.print("Content-type: " + contentType + "\r\n\r\n"); } // send the file in the string os.println(theData); theConnection.close(); } catch(IOException e) { } } 95-713

  36. // main loads the file and creates the object on every hit public static void main(String args[] ) { int thePort; ServerSocket ss; Socket theConnection; FileInputStream theFile; // cache the file try { // open file and create a DataInputStream theFile = new FileInputStream(args[0]); DataInputStream dis = new DataInputStream(theFile); 95-713

  37. // determine the content type of this file if(args[0].endsWith(".html") || args[0].endsWith(".htm") ) { contentType = "text/html"; } else { contentType = "text/plain"; } // read the file into the string theData try { String thisLine; while((thisLine = dis.readLine()) != null) { theData += thisLine + "\n"; } } catch(Exception e) { System.err.println("Error " + e); } } 95-713

  38. catch(Exception e) { System.err.println(e); System.err.println("usage: java onefile filename port"); System.exit(1); } // set the port to listen on try { thePort = Integer.parseInt(args[1]); if(thePort < 0 || thePort > 65535) thePort = 80; } catch(Exception e) { thePort = 80; } 95-713

  39. // create a server socket try { ss = new ServerSocket(thePort); System.out.println("Accepting connections on port " + ss.getLocalPort()); System.out.println("Data to be sent:"); System.out.println(theData); while(true) { // stop and wait for a connection Socket socketTemp = ss.accept(); // we have a socket so create a handler OneFile fs = new OneFile(socketTemp); // start the handler running fs.start(); } } catch(IOException e) {System.out.println("Socket error"); } } } 95-713

  40. Java 2 Collection Classes 95-713

  41. A Collection is a group of objects. A Map is a set of associations between objects. The core collection interfaces 95-713

  42. The Collection Interface • Root of a hierarchy • Some collections allow duplicates others do not • This interface allows you to pass collections around • Has generic methods such as contains() ,isEmpty(), • iterator() and size() 95-713

  43. The Set Interface Extends Collection • At most one null element • No duplicates, i.e., no elements such that e1.equals (e2) • If you try to add a duplicate then the add method • returns false 95-713

  44. The SortedSet Interface Extends Set • Guarantees that its iterator will traverse the set in ascending element order, sorted according to the natural ordering of its elements or by a comparator provided at sorted set creation. • If no comparator is specified then all elements of the set must implement the Comparable interface. • CompareTo or Compare is used. 95-713

  45. The List Interface Extends Collection • An ordered collection or sequence • Access by integer position • Access by search • Duplicates allowed • Like arrays--zero based • In some implementations, positional operations may execute in time proportional to the index value • Can return an Iterator (hasNext(), next(), remove()) or ListIterator(hasNext(), hasPrevious(), add(),…) • Add and remove can be done at end or at a particular index 95-713

  46. The Map Interface (Key, Value pairs) • Root of a hierarchy • No duplicate keys, duplicate values are okay • Three collection views • Set of keys via keySet() method • Collection of values via values() method • Set of key-value mappings via entrySet() • Methods include put(key,value) and get(key) 95-713

  47. The SortedMap Interface Extends Map A map that guarantees that it will be in ascending key order Sorted by natural ordering of its keys or by a comparator provided at SortedMap creation time Ordering must be consistent with equals. It uses the compare or compareTo methods 95-713

  48. Abstract Classes • General Notes: • Can’t be instantiated • A subclass of an abstract class can be instantiated if it • overrides each abstract method in the superclass and • provides a body for each. 95-713

  49. Abstract Classes AbstractCollection Partial implementation of the Collection interface Makes it easy to define custom Collection implementations AbstractSet, AbstractList and so on… Partial implementation of these interfaces If you want to create your own custom built Collections, start by extending the appropriate abstract class. In what follows we will be using existing (built-in) classes. 95-713

  50. Concrete Classes 95-713

More Related