Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java zJava Design Principles xSafety  Primitive data types have fixed sizes and meanings  Type safety (strongly typed)  Strict control of pointers xObject.

Similar presentations


Presentation on theme: "Java zJava Design Principles xSafety  Primitive data types have fixed sizes and meanings  Type safety (strongly typed)  Strict control of pointers xObject."— Presentation transcript:

1 Java zJava Design Principles xSafety  Primitive data types have fixed sizes and meanings  Type safety (strongly typed)  Strict control of pointers xObject Oriented Language  Everything is an object  Common base class xSimplicity

2 Java zJava features  Automatic garbage collection  Nice exception handling  Object hierarchy  Polymorphic data structures  Wrapper classes  Memory management  Cloning

3 Java API Packages package java.applet package java.awtjava.appletjava.awt package java.awt.datatransfer package java.awt.eventjava.awt.datatransfer java.awt.event package java.awt.image package java.beansjava.awt.imagejava.beans package java.io package java.langjava.iojava.lang package java.lang.reflect package java.mathjava.lang.reflectjava.math package java.net package java.securityjava.netjava.security package java.security.acl package java.security.interfacesjava.security.acl java.security.interfaces package java.sql package java.textjava.sqljava.text package java.util package java.util.zipjava.utiljava.util.zip

4 Java - Sequential Execution (Example 1) /** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Display the string. }

5 Java - Sequential Execution (Example 2) public static void main( String[ ] args ){ // Web page grep if (args.length != 2){ // Input arguments: URL, text System.out.println("Find String URL"); return; } String str = args[0]; try { URL url = new URL(args[1]); // Open connection, and use page InputStream in = url.openStream(); // as a stream StreamTokenizer tokens = new StreamTokenizer(in); int matchCount = 0; // Count the tokens which match the while(tokens.nextToken() != StreamTokenizer.TT_EOF) { // input stream if (tokens.ttype == StreamTokenizer.TT_WORD) if (str.equalsIgnoreCase(tokens.sval)) // Ignore case in looking matchCount++; // for matches } System.out.println(matchCount + " matches of " + str + " found at " + args[1]); } catch( MalformedURLException mue) { // Errors if URL is bad, or System.out.println("Bad URL"); // problems with input } catch(IOException ioe) { System.out.println("IO Error"); }

6 Locks and Synchronization (1) zA variable is any location within a Java program that may be stored into zVariables are kept in a main memory that is shared by all threads zEvery thread has a working memory in which it keeps its own working copy of variables that it must use or assign zThe main memory contains the master copy

7 Locks and Synchronization (2) zJava providing mechanisms for synchronizing the concurrent activity of threads zJava uses monitors, which are a high-level mechanism for allowing only one thread at a time to execute a region of code protected by the monitor zThe behavior of monitors is explained in terms of locks

8 Locks and Synchronization (3) zA lock associated with every object zThreads may compete to acquire a lock zNo separate lock and unlock actions; instead, they are implicitly performed by high-level constructs zJava VM does provide separate monitorenter and monitorexit instructions

9 Synchronized statement zAcquires a mutual-exclusion lock on behalf of the executing thread zFirst computes a reference to an object zThen it attempts to perform a lock action on that object and does not proceed further until the lock action has successfully completed zAfter the lock action has been performed, the body of the synchronized statement is executed zIf execution of the body is ever completed, either normally or abruptly, an unlock action is automatically performed

10 Synchronized method (1) zAgain, first computes a reference to an object zAutomatically attempt to perform a lock action zBody of method is not executed until the lock action has successfully completed zIf the method is an instance method, it locks the lock associated with the instance zIf the method is static, it locks the lock associated with the class object that represents the class zIf execution of the body is ever completed, either normally or abruptly, an unlock action is automatically performed

11 Synchronized method (2)

12 Synchronized method (3) zThe methods wait, notify, notifyAll of class zobject support an efficient transfer of control from one thread to another. Instead of “spinning”, a thread can suspend itself using wait until such time as another thread awakens it using notify zEspecially appropriate in situations where threads have a producer- consumer relationship (actively cooperating on a common goal) rather than a mutual exclusion relationship (trying to avoid conflicts while sharing a common resource) zIf two or more concurrent threads act on a shared variable, there is a possibility that the actions on the variable will produce timing- dependent results - “race condition”

13 Class java.lang.Object

14 Class java.lang.Thread zExtends java.lang.Object zMethods ycurrentThread() Returns a reference to the currently executing thread objectcurrentThread ygetName() Returns this thread's namegetName ysetName(String) Changes the name of this thread to be equal to the argument namesetName ygetPriority() Returns this thread's prioritygetPriority  setPriority(int) Changes the priority of this thread. setPriority  run() If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns run ydestroy() Destroys this thread, without any cleanupdestroy

15 Class java.lang.Thread (cont’d) yinterrupt() Interrupts this threadinterrupt yinterrupted() Tests if the current thread has been interruptedinterrupted yresume() Resumes a suspended threadresume ysleep(long) Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.sleep ystart() Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.start ystop() Forces the thread to stop executing.stop ystop(Throwable) Forces the thread to stop executing.stop ysuspend() Suspends this thread.suspend  yield() Causes the currently executing thread object to temporarily pause and allow other threads to execute. yield

16 Creating a New Thread (1) zMethod One: Declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started zExample:

17 Creating a New Thread (2)  Method Two: D eclare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started zExample:


Download ppt "Java zJava Design Principles xSafety  Primitive data types have fixed sizes and meanings  Type safety (strongly typed)  Strict control of pointers xObject."

Similar presentations


Ads by Google