1 / 81

JAVA: Chapter 6 Exception & Multithreading

JAVA: Chapter 6 Exception & Multithreading. Learning Outcome. At the end of this slide, student able to understand the concept of multithreading and exception handling. . Exception-Handling Overview . What do you think if 4 divided by 0?. Exception-Handling Overview .

erek
Télécharger la présentation

JAVA: Chapter 6 Exception & Multithreading

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: Chapter 6 Exception & Multithreading

  2. Learning Outcome At the end of this slide, student able tounderstand the concept of multithreading and exception handling.

  3. Exception-Handling Overview What do you think if 4 divided by 0?

  4. Exception-Handling Overview It is possible JAVA can calculate this equation?

  5. Exception-Handling Overview JAVA cannot calculate that equation, the output will be failed!!

  6. Exception Overview import java.util.Scanner; public class QuotientWithIf { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter two integers: "); int number1 = input.nextInt(); int number2 = input.nextInt(); if (number2 != 0) System.out.println(number1 + " / " + number2 + " is " + (number1 / number2)); else System.out.println("an integer cannot be divided by zero"); } } package quotient; import java.util.Scanner; public class Quotient { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter two integers: "); int number1 = input.nextInt(); int number2 = input.nextInt(); try { int result = number1 / number2; System.out.println(number1 + " / " + number2 + " is " + result); } catch (ArithmeticException ex) { System.out.println("Exception: an integer cannot be divided by zero"); } } }

  7. Exception Overview import java.util.*; public class InputMismatchExceptionDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); booleancontinueInput = true; do { try { System.out.print("Enter an integer: "); int number = input.nextInt(); // Display the result System.out.println( "The number entered is " + number); continueInput = false; } catch (InputMismatchException ex) { System.out.println("Try again. (" + "Incorrect input: an integer is required)"); input.nextLine(); // discard input } } while (continueInput); } }

  8. Example of Exception

  9. Other Exception • DatatypeConfigurationException • DestroyFailedException • EOFException • Exception • ExecutionException • ExpandVetoException • FileLockInterruptionException • FileNotFoundException • FishFaceException • FontFormatException • GSSException • GeneralSecurityException • IIOException • IOException • IllegalAccessException • IllegalArgumentException • IllegalClassFormatException • IllegalStateException • IndexOutOfBoundsException • InputMismatchException • InstantiationException • InterruptedException • InterruptedIOException • IntrospectionException • InvalidApplicationException • InvalidMidiDataException • InvalidPreferencesFormatException • InvalidTargetObjectTypeException • AWTException • AclNotFoundException • ActivationException • AlreadyBoundException • ApplicationException • ArithmeticException • ArrayIndexOutOfBoundsException • AssertionException • BackingStoreException • BadAttributeValueExpException • BadBinaryOpValueExpException • BadLocationException • BadStringOperationException • BatchUpdateException • BrokenBarrierException • CertificateException • ChangedCharSetException • CharConversionException • CharacterCodingException • ClassCastException • ClassNotFoundException • CloneNotSupportedException • ClosedChannelException • ConcurrentModificationException • DataFormatException

  10. ProtocolException • RefreshFailedException • RemarshalException • RemoteException • RuntimeException • SAXException • SOAPException • SQLException • SQLWarning • SSLException • ScriptException • ServerNotActiveException • SocketException • SyncFailedException • TimeoutException • TooManyListenersException • TransformException • TransformerException • URIReferenceException • URISyntaxException • UTFDataFormatException • UnknownHostException • UnknownServiceException • UnmodifiableClassException • UnsupportedAudioFileException • UnsupportedCallbackException • UnsupportedEncodingException • UnsupportedFlavorException • UnsupportedLookAndFeelException • UnsupportedOperationException • UserException • XAException • XMLParseException • XMLSignatureException • XMLStreamException • XPathException • ZipException • InvocationTargetException • JAXBException • JMException • KeySelectorException • LastOwnerException • LineUnavailableException • MalformedURLException • MarshalException • MidiUnavailableException • MimeTypeParseException • NamingException • NegativeArraySizeException • NoSuchElementException • NoSuchFieldException • NoSuchMethodException • NoninvertibleTransformException • NotBoundException • NotOwnerException • NullPointerException • NumberFormatException • ObjectStreamException • ParseException • ParserConfigurationException • PrintException • PrinterException • PrivilegedActionException • PropertyVetoException

  11. Friendly Advice about Exception • Actually, it is very difficult to remember all exception especially to junior programmer. However, the programmer can use online recourses such as: http://docs.oracle.com/javase/7/docs/api/ as assistance.

  12. System Errors System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

  13. Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.

  14. Runtime Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.

  15. Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }

  16. Catching Exceptions try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; } ... catch (ExceptionN exVar3) { handler for exceptionN; }

  17. Catching Exceptions

  18. animation Trace a Program Execution Suppose no exceptions in the statements try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement;

  19. animation Trace a Program Execution The final block is always executed try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement;

  20. animation Trace a Program Execution Next statement in the method is executed try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement;

  21. animation Trace a Program Execution Suppose an exception of type Exception1 is thrown in statement2 try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;

  22. animation Trace a Program Execution The exception is handled. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;

  23. animation Trace a Program Execution The final block is always executed. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;

  24. animation Trace a Program Execution The next statement in the method is now executed. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;

  25. animation Trace a Program Execution statement2 throws an exception of type Exception2. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;

  26. animation Trace a Program Execution Handling exception try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;

  27. animation Trace a Program Execution Execute the final block try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;

  28. animation Trace a Program Execution Rethrow the exception and control is transferred to the caller try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;

  29. Multithreading

  30. Overview of multithreading VS Which one is the most lightness? WHY??

  31. Overview of multithreading Because of in Mozilla Firefox, there are too many process inside, compared to IE (internet explorer).

  32. Overview of multithreading What will happened if the software have too many processinside?

  33. Overview of multithreading The software become slow *Slow like snails

  34. Overview of multithreading Thread == process; Multithread == multi process; That’s why we need to learn about multithreading, so then, we know what the causes of the SLOW SOFTWARE and how to prevent from develop a slow software.

  35. Creating Tasks and Threads

  36. package taskthreaddemo; public class TaskThreadDemo { public static void main(String[] args) { // Create tasks RunnableprintA = new PrintChar('a', 100); RunnableprintB = new PrintChar('b', 100); Runnable print100 = new PrintNum(100); // Create threads Thread thread1 = new Thread(printA); Thread thread2 = new Thread(printB); Thread thread3 = new Thread(print100); // Start threads thread1.start(); thread2.start(); thread3.start(); } } // The task for printing a specified character in specified times class PrintChar implements Runnable { private char charToPrint; // The character to print private int times; // The times to repeat /** Construct a task with specified character and number of * times to print the character */ public PrintChar(char c, int t) { charToPrint = c; times = t; } @Override /** Override the run() method to tell the system * what the task to perform */ public void run() { for (inti = 0; i < times; i++) { System.out.print(charToPrint); } } } // The task class for printing number from 1 to n for a given n class PrintNum implements Runnable { private intlastNum; /** Construct a task for printing 1, 2, ... i */ public PrintNum(int n) { lastNum = n; } @Override /** Tell the thread how to run */ public void run() { for (inti = 1; i <= lastNum; i++) { System.out.print(" " + i); } } }

  37. The Thread Class

  38. The Static yield() Method You can use the yield() method to temporarily release time for other threads. For example, suppose you modify the code in Lines 53-57 in TaskThreadDemo.java as follows: public void run() { for (int i = 1; i <= lastNum; i++) { System.out.print(" " + i); Thread.yield(); } } Every time a number is printed, the print100 thread is yielded. So, the numbers are printed after the characters.

  39. The Static sleep(milliseconds) Method The sleep(long mills) method puts the thread to sleep for the specified time in milliseconds. For example, suppose you modify the code in Lines 53-57 in TaskThreadDemo.java as follows: public void run() { for (inti = 1; i <= lastNum; i++) { System.out.print(" " + i); try { if (i >= 50) Thread.sleep(1); } catch (InterruptedException ex) { } } } Every time a number (>= 50) is printed, the print100 thread is put to sleep for 1 millisecond.

  40. The join() Method You can use the join() method to force one thread to wait for another thread to finish. For example, suppose you modify the code in Lines 53-57 in TaskThreadDemo.java as follows: The numbers after 50 are printed after thread printA is finished.

  41. isAlive(), interrupt(), and isInterrupted() The isAlive() method is used to find out the state of a thread. It returns true if a thread is in the Ready, Blocked, or Running state; it returns false if a thread is new and has not started or if it is finished. The interrupt() method interrupts a thread in the following way: If a thread is currently in the Ready or Running state, its interrupted flag is set; if a thread is currently blocked, it is awakened and enters the Ready state, and an java.io.InterruptedException is thrown. The isInterrupt() method tests whether the thread is interrupted.

  42. The deprecated stop(), suspend(), and resume() Methods NOTE: The Thread class also contains the stop(), suspend(), and resume() methods. As of Java 2, these methods are deprecated (or outdated) because they are known to be inherently unsafe. You should assign null to a Thread variable to indicate that it is stopped rather than use the stop() method.

  43. Deadlock  is a situation in which two or more competing actions are each waiting for the other to finish, and thus neither ever does. Ex: VENDING MACHINE (what will happened if you insert the coin and suddenly push the drink? Sometimes, the machine will return the coin or the machine will do nothing)

  44. Thread Priority • Each thread is assigned a default priority of Thread.NORM_PRIORITY. You can reset the priority using setPriority(int priority). • Some constants for priorities include Thread.MIN_PRIORITYThread.MAX_PRIORITYThread.NORM_PRIORITY

  45. Example: Flashing Text

  46. /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package executer; import javax.swing.*; public class Executer extends JApplet implements Runnable { private JLabeljlblText = new JLabel("Welcome", JLabel.CENTER); public Executer() { add(jlblText); new Thread(this).start(); } @Override /** Set the text on/off every 200 milliseconds */ public void run() { try { while (true) { if (jlblText.getText() == null) jlblText.setText("Welcome"); else jlblText.setText(null); Thread.sleep(200); } } catch (InterruptedException ex) { } } /** Main method */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame("FlashingText"); frame.add(new Executer()); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 200); frame.setVisible(true); } }); } }

  47. GUI Event Dispatcher Thread GUI event handling and painting code executes in a single thread, called the event dispatcher thread. This ensures that each event handler finishes executing before the next one executes and the painting isn’t interrupted by events.

  48. invokeLater and invokeAndWait In certain situations, you need to run the code in the event dispatcher thread to avoid possible deadlock. You can use the static methods, invokeLater and invokeAndWait, in the javax.swing.SwingUtilities class to run the code in the event dispatcher thread. You must put this code in the run method of a Runnable object and specify the Runnable object as the argument to invokeLater and invokeAndWait. The invokeLater method returns immediately, without waiting for the event dispatcher thread to execute the code. The invokeAndWait method is just like invokeLater, except that invokeAndWait doesn't return until the event-dispatching thread has executed the specified code.

  49. Launch Application from Main Method So far, you have launched your GUI application from the main method by creating a frame and making it visible. This works fine for most applications. In certain situations, however, it could cause problems. To avoid possible thread deadlock, you should launch GUI creation from the event dispatcher thread as follows: public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { // Place the code for creating a frame and setting it properties } }); }

  50. Thread Synchronization A shared resource may be corrupted if it is accessed simultaneously by multiple threads. For example, two unsynchronized threads accessing the same bank account may cause conflict.

More Related