《JAVA 2 学习指南》笔记(英文版)

这是我在备考SCJP考试时阅读 〈JAVA 2学习指南〉所摘录的笔记,经过整理后拿出来与各位分享!
JAVA 2 学习指南》笔记
Sun Certified Programmer for Java 2 (Exam 310-035)
Author: Andy Hong   Time:2006.5. 1 ——5.10
I.          Language Fundamentals
ü        Java Programming Language Keywords
1)        Part List of Java Keywords : const, goto, instanceof, native, strictfp, transient, volatile, assert
2)        Two Unused Reserved Words: const, goto. The two words are reserved in java but which are not used, if you try to use one of them the java compiler will not successes
3)        Notice : null, false, true are not keywords
4)        All keywords start with a lowercase letter
ü        Literals and Ranges of All Primitive Data Types
1)        Ranges of Primitive Numbers: byte(8 bits) , short(16 bits) , int(32 bits), long(64 bits) , float(32 bits) , double(64 bits) .All these are signed
2)        Type Boolean can be only true or false. The bit depth of a boolean is virtual-machine dependent
3)        Type char is unsigned 16-bit integers , which ranging from 0 ~65535 .char is really an integer type ,it can be assigned to any number type large enough to hold 65535.You can represent a char literal like this: char c=’a’(as a single character) or char c=’/u004E’(as a Unicode value) ;you also can assign a number literal to a char variable like this(as a integer): char c=012 or char c=15 or char c=0x15 or char c=(char)-55 or char c=(char)65536
4)        There are three ways to represent integer numbers(contains byte, short, int ,long ,char)in java language: decimal(10-based), octal(8-based prefix 0),hexadecimal(16-based,prefix 0x or 0X)
5)        Floating-Point Literals are defined as double by default, if you want to assign a FP literal to a variable of type float, you must attach the suffix F or f to the number. You may also attach D or d to double literals
, but it is not necessary
6)        Notice that strings are not primitives
ü        Array Declaration, Construction, and Initialization
1)        Remember that arrays must always be given a size at the time they are constructed
2)        Arrays can hold primitives or objects ,but the array itself is always an object
3)        Multidimensional Arrays are arrays of arrays. Notice that only the first brackets must be given a size : int [][] a=new int[2][] ,unless you are creating an anonymous array like 4)
4)        Remember that you do not specify a size when using anonymous array creation syntax like this: int [] a=new int[ ]{1,3}
5)        You will get a NullPointerException if you try to: Calling the instance method of a null object;  Accessing or modifying the field of a null object.; Taking the length of null as if it were an array.; Accessing or modifying the slots of null as if it were an array.; Throwing null as if it were a Throwable value.
6)        Arrays have a length variable that contains the number of elements in the array
7)        An array of primitives can accept any value that can be promoted implicitly to the declared type of the array, an array of objects can hold any object that passes IS-A test for the declared type of the array
ü        Using a Variable or Array Element That is Uninitialized and Unassigned
1)        Default values for primitive types: byte, short ,int ,long( are all 0); float, double(are all 0.0); boolean (false); char(‘/u0000’)
2)        Default value for object types: null
3)        All primitives and objects which are uninitialized and unassigned can get default value if they are declared as instance
4)        All primitives and objects (except Arrays) must be initialized before they are used if they are declared as local variables
5)        Array elements can get the default values regardless of whether the array is declared as an instance or local variable
ü        Command-Line Arguments to Main
1)        If no arguments are passed to main ,the length of the main string array parameter will be zero
II.       Declarations and Access Control
ü        Declarations and Modifiers
1)        Four access controls(public, protected, default, private) work for most method and variable declarations, but a non-inner class can be declared with only public or default access
2)        When we say code from one class(class A) has access to another class(class B) ,it means class A can do one of three things: create an instance of class B ; extend class B; access certain methods and variables in class B, depending on the access control of those methods and variables
3)        Notice that strictfp is a keyword and can be used to modify a class or a method, but never a variable
4)        First look at the access level of the class. If a class cannot be accessed, its member cannot be accessed. So determine class visibility before determining member visibility
5)        A subclass cannot see, use, or even think about the private members of its superclass
6)        Remember that a private method cannot be overridden by a subclass
7)        No matter if the superclass and subclass are in different package, the protected superclass member is still visible to the subclass. But notice that subclass outside the package can only inherit a protected member, but cannot use a superclass reference to access a protected member. And once the subclass-outside-the-package inherits the protected member of the superclass ,that member(as inherited by the subclass)becomes private to any code outside the subclass
8)        Local variable declarations cannot have access modifiers. Notice that the only modifier that can be applied to local variables is final (none other)
9)        Four access controls: private only the same class; default in the same class, any class in the same package, and subclass in the same package; protected in the same class , any class in the same package, subclass in the same package or outside the package; public all
10)    Abstract methods cannot be marked as final, private, synchronized, strictfp, native, static
11)    No matter where they declared, static variables will be initialized before non-static variables.
12)    You can't override an non-static method with static method. And You can't override a static method with non-static method. But static method can overridden a static method.
13)    Now see the comparison: local variables modifier(only final); non-local variables modifiers(final, public ,protected, private, static, transient, volatile); methods modifiers(final ,public ,protected, private, static, abstract, synchronized, strictfp, native) ; class modifiers(final, public, abstract, strictfp)
14)    A local variable cannot be referenced in any code outside the method in which it is declared
15)    A static method cannot access a nonstatic (instance) member---method or variable
ü        Declaration Rules
1)        The can be only one public class per source code file
2)        The name of the file must match the name of the public class
3)        The order is: package ; import ; class
4)        There can be only one package statement per source code file, but can have multiple import statements
5)        File with no public class have no naming restrictions
6)        The rules to the main() method: it must be static ,must be void ,must have a single String array argument(we can name the argument anything0, must be public, the order of public and static can be switched, and other overloaded methods named main( ) can exist legally in the class
7)        If you do not have a proper main( ) method (means have no main( ) method rely all the rules above), there will cause a runtime error(not a compiler error, please remember)
ü        Interface Implementation
1)        All interface methods are implicitly public and abstract
2)        Interfaces are public and abstract by default
3)        All interface variables are implicitly public static final
4)        Interface methods must not be static
5)        Remember interface methods are abstract ,so they cannot be marked final, native, strictfp, synchronized
6)        A class implementing an interface can be abstract , which does not have to implement the interface methods
7)        An interface can not extend anything but one or more other interface
8)        An interface can not implement another interface or class
9)        Notice that java.lang.Runnable interface, which has a single method we must implement: public void run( ){ }
III.     Operators and Assignments
ü        Java Operators
1)        The result of an expression involving anything int-sized or smaller (byte, short) is always an int. In other words , add two bytes together will get an int, multiply a byte and a short will get an int , and so on
2)        Variables are just bit holders with a designated type
3)        When creating a new object , e.g., Button b=new Button( ); ,three things happen: make a reference variable named b of type Button ; create a new Button object; refer the reference variable b to the Button object
4)        When floating-point numbers are divided by zero , they return positive or negative infinity , except when the dividend is also zero , in which case we get NaN ; when the remainder operator( %) performs a floating-point divide by zero , it will not cause a runtime exception
5)        When integers are divided by zero or when the remainder operators performs an integer divide by zero, a runtime Arithmetic Exception is thrown
6)        To object variables, the contents of a reference variable are a bit pattern, so if we assign reference variable a to reference variable b, the bit pattern in a is copied and the new copy is placed to b, the two reference variables hold the same bit pattern. When we made a change to either of the reference variable, both of the reference variables will change. But please remember this is not fit for String object
7)        Shift operators: >> (right shift); >>> (unsigned right shift); << (left shift). Besides, please remember shift operators can only be used on integer types (byte, short, int, long) and on all bases of integers (octal, decimal, hexadecimal). For int shifts>32 or long shifts>64 , the actual shift value is the remainder of the right operand / divided by 32 or 64
ü        Logical Operators
1)        The short-circuit operators (&&and | | ) can be used only in logical expressions. The bitwise operators( & and | ) can be used in both logical and bitwise expressions
2)        The && does not evaluate the right operand if the left operand is false ; the | | does not evaluate the right operand if the left operand is true
3)        The & and | always evaluate both operands
ü        Passing Variables into Methods
1)        Method arguments are always copie s ——of either primitive variables or reference variables
2)        Method arguments are never actual objects (they can be reference to objects)
3)        Remember that a reference variable holds bits that represent a way to get to a specific object in memory
4)        When object variables is passed into a method , any changes to the object that occur inside the method are being made to the object whose reference was passed
5)        When primitive variables is passed into a method , it is passed by value , which means pass-by-copy-of-the-bits-in-the-variable
IV.    Flow Control, Exceptions, and Assertions
ü        Writing Code Using if and switch Statements
1)        Switch statements can evaluate only the byte, short, int , char data types
2)        The case argument must be a literal or final variable
3)        The default block can be located anywhere in the switch block,
ü        Writing Code Using Loops
1)        A variable declared in the for loop declaration cannot be accessed outside the for loop
2)        The do-while loop will enter the body of the loop at least once, even if the test condition is not met
ü        Handling Exceptions
1)        Exceptions come in two flavors: checked and unchecked. Checked exceptions include all subtypes of Exception , subtypes of Error or RuntimeException are unchecked exception .You are free to declare or handle the unchecked exception , but checked exception are subject to the handle or declare rule
2)        Any method that might throw a checked exception (including methods that invoke methods that can throw a checked exception) must either declare the exception using the throws keyword , or handle it with an try/catch
3)        If a method throws a checked exception , it must declare it in the method declaration
4)        The handlers for the most specific exceptions must always be placed above those for more general exceptions
5)        The finally block will always be invoked, but the only one case that finally block will not start is that if code from the try or catch blocks calls System. exit( )
6)        You can have try and finally or try /catch and finally or try and catch, but cannot have only try
ü        Working with the Assertion Mechanism
1)        Assertions can have either one or two expressions, the first expression must always result in a boolean value, the second expression can be anything that results in a value(not void)
2)        We can use “assert” as a keyword or as an identifier, but not both
3)        Once you have written your assertion code , we can choose to enable or disable them, but remember that assertions are disable default
4)        We know that assertions are disabled at runtime by default. To enable them , use a command-line flag –ea or –enableassertions, you can selectively disable them using the –da or –disableassertions flag
5)        We can enable or disable assertions in the system classes with the –esa or –dsa flag. We can enable or disable assertions on a class-by-class basis using the following syntax: java –ea -da: MyClass TestClass.
6)        Though AssertionError is a subclass of Throwable , don’t catch it , if you do it , it should be a exception
V.       Object Orientation, Overloading and Overriding, Constructors, and Return Types
ü        Benefits of Encapsulation
1)        The goal of encapsulation is to hide implementation behind the interface
2)        Encapsulated code has two features : instance variables are kept protected (usually with the private modifier) ; getter and setter methods provide access to instance variables
3)        IS-A refers to inheritance
ü        Overridden and Overloaded Methods
1)        The rules of overriding a method are as follows:
n        The argument list and return type and name must exactly match that of the overridden method
n        The access level must not be more restrictive than that of the overridden method
n        The overriding method must not throw new or broader checked exceptions , it can only throw narrower or fewer exceptions and Runtime exceptions
n        We cannot override a method marked final
n        Remember that the Object type determines which method is used at runtime
2)        The rules of overloading a method :
n        We must change the argument list
n        We can change the return type and the access modifier , and can declare new or broader checked exceptions
n        We can not change the method name
n        A method can be overloaded in the same class or in the subclass
n        Remember that reference type determines which overloaded version is used at compile time.
3)        Methods from a superclass can be overridden and overloaded in the subclass
4)        Polymorphism applies to overriding , not to overloading
ü        Constructors and Instantiation
1)        Rules for constructors:
n        Constructors can use any access modifier , including private
n        The constructor name must match the class name , and constructors must not have a return type
n        If we do not type a constructor into the class code , a default constructor with no-arg will be automatically generated by the compiler
n        Every constructor must have as its first statement either a call to an overloaded constructor (this ( )) or a call to the superclass constructors (super ( )), but we can not have both. .
n        If we do not type in the call to super ( ), the compile will insert a no-arg call to super ( ) for us. But if our super constructor has arguments, we must type in the call to super () supplying the appropriate arguments in the subclass. So if our superclass does not have a non-arg constructor, then we will not be able to use the default constructor supplied by the compile in our subclass
n        Constructors are never inherited , they cannot be overridden , but they can be overloaded
n        Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated.
n        Interface do not have constructors
2)        Constructors execution occurs as follows :
n        The constructors calls its superclass constructor ,which calls its supercalss constructor , and so on all the way up to the Object constructor
n        The Object constructor executed and then returns to the calling constructor, which runs to completion and then returns to its calling constructor , and so on back down to the completion of the constructor of the actual instance being created
ü        Legal Return Types
1)        An array is a perfectly legal return type
2)        In a method with an object reference return type, we can return any object type that can be implicitly cast to the declared return type
3)        For methods with an interface return type , any implementer of that interface can be returned
VI.    Java. lang—The Math Class, Strings, and Wrappers
ü        Using the java.lang.String Class
1)        Notice that: substring (int begin, int end). It is substring, not subString. The first argument begin is zero-based, but the second argument end is not zero-based
2)        The String class is final , the methods of which cannot be overridden
3)        String have a method named length( ), while arrays have an attribute named length
4)        String objects are immutable , but String reference variables are not
5)        StringBuffers are mutable
6)        StringBuffer equals( ) is not overridden , it does not compare values but memory addresses
ü        Using the java.lang.Math Class
1)        The abs( ) method/ max( )/ min( ) is overloaded to take an int, a long , a float ,or a double, and returns int, long, float, or double
2)        The abs( ) method can return a negative if the argument is the int or long value equal to the value of Integer.MIN_VALUE or Long.MIN_VALUE
3)        The random( ) returns a double greater than or equal to 0.0 and less than 1.0 .Notice that the random( ) does not take any arguments
4)        The ceil ( ) method returns a double which is greater than or equal to the argument, while the floor ( ) returns a double which is less than or equal to the argument. Remember that ceil( ) and floor( ) take only doubles
5)        The round ( ) is overloaded to take a float or a double, which returns an int if it was passed a float or returns a long if it was passed a double. The round( ) returns the integer closest to the argument
6)        The methods sin( ), cos( ), tan( ) take a double angle in radians , and all of which return doubles
7)        The sqrt ( ) takes a double and returns a double. Notice it can return NaN if the argument is NaN or less than zero
8)        NaN is not equal to anything , not even itself
ü        Using Wrapper Class
1)        The wrapper classes correlate to the primitive types
2)        Wrapper constructors can take a String or a primitive , except for Character , which can only take a char
3)        Three most important methods:
n        xxxValue( ) : takes no arguments , returns a primitive
n        parseXxx( ) : takes a String , returns a primitive , is static , throws NFE
n        valueOf( ) : takes a String , returns a wrapped object , is static
4)        Radix refers to bases other than 10; binary is radix 2; octal is 8; hex is 16
ü        Using the equal( ) Method with Strings and Wrappers and Objects
1)        == compares bit patterns , either primitive bits or reference bits
2)        Primitive variables must use == , they cannot use equals( ) method
3)        Notice that equals( ) is used only to compare objects
4)        The StringBuffer class has not overridden equals( )
5)        The String and wrapper classed are final and have overridden equals( )
6)        The compile will not allow == if the classes are not in the same hierarchy
7)        Wrappers will not pass equals( ) if they are in different classes
VII.  Objects and Collections
ü        Overriding hashCode( ) and equals( )
1)        The critical methods in class Object are equals ( ), hashCode ( ), toString ( ), finalize ( ). And equals( ), hashCode( ), toString( ) are public ( finalize( ) is protected)
2)        Overriding the toString ( ) method when you want a mere mortal to be able to read something meaningful about the objects of your class. For example , when you pass an object reference to the System.out.println( obj) method ,the toString( ) method is called
3)        Use == to determine if two reference variables refer to the same object
4)        Use equals ( ) to determine if two objects are meaningfully equivalent
5)        If we do not override equals( ) , our objects will not be useful hashtable/hashmap keys and two different objects can not be considered the same
6)        String and wrappers override equals( ) and make good hashtable/hashmap keys
7)        When override equals( ) , use the instanceof operator to be sure we are evaluating an appropriate class and compare the objects’ significant attributes
8)        Remember: public boolean equals (Object o) { }. we must override the equals( ) like this
9)        If x.equals(y) is true, then x.hashCode()==y.hashCode( ) must be true
10)    If we override equals( ) , override hashCode( ) as well
11)    If two objects are equal , their hashcodes must be equal as well
12)    It is legal for a hashCode ( ) methods to return the same value for all instances
13)    The hashCode( ) contract:
n        If x .equals( y) is true , x .hashCode( )==y .hashCode( ) must be true
n        If x .equals( y) is false , x .hashCode( )==y .hashCode( ) can be either true or false
n        If x .hashCode( )==y .hashCode( ) is true , x .equals(y) can be true
n        If x .hashCode( )==y .hashCode( ) is false , x .equals(y) must be false
14) Transient variables are not appropriate for equals ( ) and hashCode ( )
ü        Collections
1)        Notice that :
n        The collection(lowercase ‘c’) , which represents any of the data structures in which objects are stored and iterated over
n        The Collection(capital ‘C’) , which is actually the java.util.Collection interface form which Set and List extend
n        The Collections(capital ‘C’ and ends with ‘s’) , which is actually the java.util.Collections class holds a pile of static utility methods for use with collections
2)        Three basic flavors of collections :
n        Lists of things : Ordered , duplicates allowed , with an index
n        Sets of things : may or may not be ordered and/or sorted , duplicates not allowed
n        Maps of things : may or may not be ordered and/or sorted , duplicates not allowed
3)        Four basic subflavors of collections :
n        Ordered : means iterating through a collection in a specific , nonrandom order
n        Sorted : means iterating through a collection in a natural(natural means alphabetic, numeric, or programmer-defined , whichever applies) sorted order
n        Unordered
n        Unsorted
4)        Key attributes of common collection classed:
n        List interface :
Ø        ArrayList : fast iteration and fast random access ; not sorted ; ordered by index ; duplicates allowed ;implements RandomAccess interface(only ArrayList and Vector implements the interface)
Ø        Vector : is basically the same as an ArrayList , but Vector methods are synchronized(only Vector and Hashtable methods are synchronized) for thread safety
Ø        LinkedList : may iterate more slowly than an ArrayList , but fast insertion(adding) and deletion(removing) , i.e. , stacks and queues ; not sorted ; ordered by index ; duplicates allowed ;
n        Set interface :
Ø        HashSet : not sorted ; not ordered ; duplicates not allowed ;
Ø        LinkedHashSet : not sorted ; duplicateds not allowed ; ordered; iterates by inserting order or last access
Ø        TreeSet : duplicateds not allowed ; sorted by natural order(only TreeSet and TreeMap are sorted collections) ; iterates in natural sorted order
n        Map interface :
Ø        HashMap : fastest updates ; not sorted ; not ordered ;allows one null key and many null values ;
Ø        LinkedHashMap : faster iterations ; not sorted ; ordered by insertion order or last access order ; allows one null key and many null values ;
Ø        Hashtable : notice that is Hashtable not HashTable ; like a slower HashMap ; not sorted ; not ordered ; allows no null keys and no null values
Ø        TreeMap : sorted in natural order
ü        Garbage Collection
1)        In java , garbage collection provides some automated memory management
2)        All objects in java live on the heap
3)        The heap is also known as the garbage collection heap
4)        The purpose of garbage collecting is to find and delete objects that cannot be reached
5)        Only the JVM decides exactly when to run the garbage collector
6)        We can only recommend when to run the garbage collector
7)        We can not known the garbage collection algorithm
8)        Objects must be considered eligible before they can be garbage collected
9)        An object is eligible when no live thread can reach it
10)    To reach an object , a live thread must have a live , reachable reference variable to that object
11)    Java applications can run out of memory
12)    To reiterate : garbage collection cannot be forced
13)    Request garbage collection with System.gc( )
14)    Class Object has a finalize ( ) method
15)    The finalize( ) method is guaranteed to run once and only once before the garbage collector deletes the object
16)    Since the garbage collector makes no guarantees , finalize( ) may never run
17)    We can uneligibilize an object from within finalize( )
18)    Ways to make objects eligible for collection:
n        Set the reference variable that refers to the object to null
n        Set the reference variable to refer to another object
n        If an object is returned from the method, it will not be eligible for collection. But objects that are not returned from the method will be eligible form collection
n        Islands of isolating :
19)    There is no guarantees the JVM will actually remove all of the unused objects from the memory
20)    In order to get the Runtime instance , we can use the method Runtime.getRuntime( )
21)    After calling the System.gc( ) method , we will have as much memory as possible
VIII.             Inner Classes
ü        Inner Classes
1)        An inner class instance has access to all members of the outer class , even those marked private
2)        The following modifiers can be applied to an inner class : abstract ; final ; public ; protected ; private ; static( turns it into a top-level class rather than an inner class); strictfp
3)        To instantiate an inner class , we must have a reference to an instance of the outer class
4)        Form code within the enclosing class , we can instantiate the inner class as follows : MyInner mi=new MyInner( );
5)        Form code outside the enclosing class, we can instantiate the inner class as follows: MyOuter. MyInner inner=new MyOuter ( ). new MyInner ( ); or MyOuter mo=new MyOuter ( ); MyInner inner=mo. new MyInner( );
6)        From code within the inner class, the keyword this holds a reference to the inner class instance. To reference the outer this we must do like follows : MyOuter.this;
ü        Method-Local Inner Classes
1)        A method-local inner class can be instantiated only within the method where the inner class is defined , but after the class definition code
2)        Like regular inner class , the method-local inner class can use all members of the outer class even its private members
3)        The inner class object cannot use the local variables(including parameters) of the method (unless the local variables are marked final) where the inner class is defined
4)        The only modifiers applied to the method-local inner class are: abstract or final (not both). Unlike the regular inner class , we can not use : public , protected, private, static , strictfp
5)        Remember that : a method-local inner class declared in a static method has access to only static members of the outer class
ü        Anonymous Inner Classes
1)        Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface. . Like this: Foo f=new Foo ( ) {……};
2)        An anonymous inner class is always created as part of statement
3)        Because of polymorphism, the only methods you can call on an anonymous inner class reference are those defined in the reference variable class (or interface). This is no different form any other polymorphic references.P470
4)        An anonymous can extend one class or implement one interface , but not both and we cannot implement more than one interface(this is unlike non-anonymous classes)
5)        An argument-defined anonymous inner class is declared, defined, and automatically instantiated as part of a method invocation. Like this: Bar b=new Bar (new Foo ( ) {……});
ü        Static Nested Classes
1)        Static nested classed are inner classes marked static modifier
2)        A static nested class is not an inner class , but instead is considered a top-level nested class
3)        Because the nested class is static , it does not have access to the instance variables and methods of the outer class
4)        Instantiated a static nested class as follows : MyOuter .Nested n=new MyOuter .Nested ( ) ; (a little different form regular inner class)
IX.    Threads
ü        Defining, Instantiating, and Starting Threads
1)        Keep in mind that we are free to overload the run( ) method in our Thread subclass
2)        The constructors of Thread are :
n        Thread( )
n        Thread(Runnable target)
n        Thread(Runnable target , String name)
n        Thread(String name)
n        Thread(ThreadGroup group , Runnable target , String name)
n        Thread(ThreadGroup group , Runnable target )
n        Thread(ThreadGroup group , String name)
`      3) There is not guaranteed that says threads will running in the order in which they were started (in other words, the order in which start ( ) was invoked on each thread)
3)        Remember that a series of threads are started in a particular order does not mean they will run in that order
4)        We can call start( ) on a Thread object only once .If start( ) is called more than once on a thread object , it will throw a RuntimeException
5)        The running thread will be of equal or greater priority than the highest priority threads in the pool
6)        Thread states
n        New: after the Thread instance has been instantiated, but the start ( ) method has not been invoked. At this point , the thread is considered not alive
n        Runnable : after the start( ) method has been invoked , at this point , the thread is considered alive
n        Running : the scheduler chooses a thread from the runnable pool
n        Waiting/blocked/sleeping: in these states the Thread is considered alive, but not runnable .If a particular event occurs the thread may return to a runnable state later.
n        Dead: when its run ( ) method completes .Once a thread is dead, it can be never be brought back to life. If you invoke start( )method on a dead Thread instance , you will get a runtime (not compiler) exception
7)        Transitioning between thread states:
New      Runnable       Running        Dead
 
              Waiting/blocked
Notice that there are several ways to get to the runnable state, but only one way to get to the running state: the scheduler chooses a thread from the runnable pool.
Notice that only one thread can be running at a time , although many threads may be in the runnable state
ü        Preventing Thread Execution
1)        Sleeping: is a static method of Thread.
2)         Notice that the sleep( ) can throw a checked InterruptedException .
3)        Remember when a thread wakes up from sleep it simply goes back to the runnable state not the running state.
4)         Another we must remember is that the time specified in sleep( ) is the minimum duration but not the exact duration in which the thread will not run
5)        One thread can not tell another thread sleep.
6)        We can use setPriority( ) method to give a thread priority between 1 and 10. Priority are not guaranteed , and not all JVMs use a priority of 1 ——10
7)        If not explicitly set , a thread’s priority will be the same priority as the thread that created the thread
8)        When one thread calls the join( ) method of another thread , the currently running thread will wait until the thread it joins with has completed.
ü        Synchronizing Code
1)        To protect the data, mark the variables private and synchronized the code that change the variables
2)        Only methods or code block of methods can be synchronized , not variables
3)        To synchronize a block of code , we must specify an argument that is the object whose lock we want to synchronize on
4)        While only one thread can be accessing synchronized code or synchronized methods , multiple threads can still access the same object’s unsynchronized code or unsynchronized methods
5)        Each object only has just one lock
6)        If a thread goes to sleep , it takes its locks with it
7)        Static methods can also be synchronized, using the lock from the java.lang.Class instance representing that class
ü        Thread Interaction
1)        Remember that wait( ), notify( ) , notifyAll( ) must be called from within a synchronized context
2)        It is common to find code such as follows :
synchronized (anotherThreadObject)
try {
       anotherThreadObject.wait ( );
       } catch (InterruptedException e) { }
The preceding code waits until notify ( ) is called on anotherThreadObject like this:
synchronized (this) {
 notify ( );
       }
3)        When the wait ( ) method is invoked on a thread object, the thread executing that code gives up its lock on the object immediately. However, when notify ( ) is called, that does not mean the lock becomes available at that moment. If the thread is still completing synchronized code, the lock is not released.
4)        Key thread methods:
n        Class Object : wait( ) ; notify( ) ; notifyAll( )
n        Class Thread : start( ) ; join( ); run( ); sleep( ) (static); yield( ) (static)
n        Interface Runnable : run( ) (just one method)
 
The end.
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值