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

Java Spring Boot 全面学习指南 通过系统学习官方文档、经典书籍与实战课程,结合开源项目实践,能够快速掌握 Spring Boot 的核心能力。 阅读详情
这是我在备考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 copies——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.
 
2、Java编程入门与学习指南 本文是一篇Java编程的入门与学习指南,详细介绍了Java语言的重要性、适用人群、学习目标及内容安排。涵盖了Java SE和Java EE的基础知识与核心技术,以及JDK的安装配置和第一个Java程序的编写。文章还提供了学习路线、资源推荐和实践项目建议,旨在帮助初学者系统化学习Java编程,具备开发商业应用的实践技能。 阅读详情

相关推荐

1、Java认证学习指南:开启你的Java职业之路

本博客详细介绍了Java认证的重要性及其学习路径,涵盖Java语言基础、面向对象编程、异常处理、多线程编程、集合框架以及输入输出流等核心内容。通过丰富的代码示例和深入浅出的解析,帮助读者系统性地掌握Java编程技能,为顺利通过Java认证考试及职业发展奠定坚实基础。

ik678901的博客 155

the name of a constructor must match the name of the enclosing class

解决:调整 命令码所在层级。构造器名匹配封闭类名。命令码的位置关系不对。

yanhaijunyan的博客 745

深入学习Java:英文版教程与实践

Java是一种面向对象的编程语言,它提供了一系列基础语法用于开发各种应用。作为程序员,掌握Java的基础语法是构建复杂程序结构的前提。在Java中,构造器(Constructor)是一种特殊的方法,它在创建对象时被调用,用来初始化对象的成员变量。构造器的名字必须与类名相同,且没有返回类型,也不用显式地返回任何数据。每个类可以拥有多个构造器,这种机制称为构造器重载(Constructor Overloading)。Java构造器的类型通常分为无参构造器和带参数构造器。

weixin_35294091的博客 976

17.2 Class members

The members of a class consist of the members introduced by its class-member-declarations and the membersinherited from the direct base class.class-member-declarations:class-member-declarationclass-me

★★创造未来★★ 1173

JAVA学习指南 .pdf

很好的java学习书籍,讲解的很清楚,由浅入深,适合初学者。

Java2学习指南

java资源的书 java2学习指南 文档

java 构造函数 调用 构造函数,java错误:构造函数调用必须是构造函数中的第一个语句...

The following code returns me an error saying:"constructor call must be the first statment in a constructor."I dont get it. The constructor in my code is the first statement. What am I doing wrong?pub...

weixin_39693950的博客 427

ubuntu打实时内核补丁教程以及安装后显卡驱动问题解决方法

在ubuntu20.04上安装成功,亲测有效 目录ubuntu打实时内核补丁教程1、下载实时内核2、解压和打补丁(patch)3、安装依赖和编译安装4、修改一些文件,便于之后切换内核5、重启电脑实时内核版本下安装nvidia显卡驱动的问题1、先切换回之前的内核(非实时)版本2、重装之前内核(非实时)版本下的显卡驱动3、切换回实时内核(按照上面的步骤)4、在实时内核下安装显卡驱动 ubuntu打实时内核补丁教程 安装目标系统:ubuntu20.04 电脑配置:i9,2080ti 1、下载实时内核 打开终端,输

weixin_39275295的博客 7995

c# 构造函数 析构函数_C#构造函数和析构函数的能力问题和解答

c# 构造函数 析构函数 1) There are following statements are given below, which of them are correct about constructors in C#.NET? Constructors are not required in a class.Constructors are used to initializing...

cumtb2009的博客 497

告别sgmediation!Stata中介效应分析新选择:mediation包完整操作指南

本文介绍了Stata中介效应分析从传统sgmediation命令向mediation包的范式升级。重点阐述了如何使用medeff和medsens命令进行更严谨的因果推断,并执行关键的敏感性分析,以评估结果对未观测混杂的稳健性,为学术研究提供发表级的分析工具。

redis7keeper的博客 1157

逆向解析手淘x-sign签名算法:从抓包到API调用的完整实践

本文详细解析了手淘x-sign签名算法的逆向过程,从抓包工具选择到API调用实践,提供了完整的解决方案。通过分析签名参数组成和生成机制,帮助开发者理解并实现淘宝接口的合法调用,同时强调了安全与合规的重要性。

weixin_29323273的博客 597

java 匿名内部类_Java 匿名内部类的示例介绍

匿名内部类的示例介绍1.方法中的内部类public class InnerClass {public void LocalOne() {class DeepInside {DeepInside() {System.out.println("方法中的内部类");}}new DeepInside();}// new DeepInside();外部无法调用public static void main(...

weixin_30781905的博客 559

以太网传输硬件设计大全

1.网线的介绍RJ45由插头和插做组成,也就是我们常说的网口和网线。RJ45 网线插头又称水晶头,共有八芯做成。RJ45网络传输线分为直通线、交叉线和全反线。直通线用于异种网络设备之间的互连,例如,计算机与交换机。交叉线用于同种网络设备之间的互连,例如,计算机与计算机。全反线用于超级终端与网络设备的控制物理接口之间的连接。下面将介绍一下各线的作用和区别。1.直通线:又叫正线或标准线,两端采用568B做线标准,注意两端都是同样的线序且一一对应。直通线是应用最广泛,现在最常用的线。

weixin_45365488的博客 6749

Spring Boot 2 学习指南与资料分享

虽有自动配置,但项目常需自定义。掌握用 @Value 注解或 @ConfigurationProperties 注解读取配置注入组件,理解配置优先级,灵活管理项目配置。

zsnandzmn的博客 1089

车载以太网抓包实战:100BASE-T1/1000BASE-T1高效监控方案解析

本文深入解析了车载以太网100BASE-T1/1000BASE-T1的高效抓包监控方案。针对智能汽车开发中的故障排查与性能测试需求,详细对比了交换机镜像、TAP分流和捕获模块三大主流方案的原理、核心优势与适用场景,并提供了基于实战经验的选型指南与操作避坑要点,帮助工程师精准定位网络问题。

desk3的博客 427

手把手教你学Simulink--移动机器人多轮协同场景实例:基于Simulink的双轮差速PMSM轮毂电机协同驱动仿真

本文介绍了基于Simulink的双轮差速PMSM轮毂电机协同驱动仿真系统。针对移动机器人存在的电机参数不一致、负载分配不均等问题,提出主从同步+力矩补偿的协同控制策略。通过搭建包含运动学模型、PMSM电机模型和矢量控制器的仿真系统,实现了速度同步误差<0.005m/s、轨迹跟踪误差<0.8cm、能耗降低12.5%的优化效果。文章详细阐述了建模步骤、核心算法实现和性能验证,为移动机器人动力系统设计提供了实用参考方案。

MHD0815的博客 131

从Java到Go:Java工程师的Golang学习指南

作为一名Java工程师,你可能已经习惯了Java的面向对象编程、强大的生态系统以及丰富的工具链。然而,随着Go语言(Golang)在云计算、微服务和并发编程领域的崛起,学习Go语言成为了一个非常有价值的选择。本文将通过对比Java和Go语言的方式,帮助你快速掌握Go语言的核心概念,并通过详细的案例讲解,帮助你理解两者之间的异同。 Go 对比: Go 对比: Go 对比: Go 对比:Java通过类和接口实现多线程编程,或者使用包中的高级并发工具。 Go Go语言通过实现并发,是轻量级的线程,由Go运

SunnyRivers 1750

Week 9 10 Neural Networks

Week 9 10 Neural Networks

金州饿霸吃不饱的博客 403

Carson带你学Android:请收好这一份全面&详细的Android学习指南

以自身的经验 & 所见所闻,旨在告诉大家,针对Android,需要学习什么知识、怎么学习 & 怎么应用到实际项目中,希望你们会喜欢。

Carson带你学Android 1万+

3D iToF深度分辨率测量

本文展示了RGB-D传感器在三维测量中的高精度表现。标靶深度图显示其具备清晰、低噪、无干扰的特性,点云数据完整度高且轮廓分明。该技术已成功应用于物流(体积测量误差<1%)、工业(高反光部件装配检测)和农业(果蔬成熟度分级)等领域,验证了其硬件和算法的可靠性,能够满足不同场景下的三维测量需求。

dream it possible 252

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Java API 英文版

参考原版文档才是硬道理,JDK API英文版、带索引、chm文档下载   http://javadoc.allimant.org/ 文档名 下载地址 大小 J2SE 5 http://javadoc.allimant.org/dist/jdk150.zip  43 Mb ...

A+ 907

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Java多线程学习指南

Java 多线程学习指南

感谢阅读 1558

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

java JDK1.8 API文档免费下载(中英文版)

jdk文档中文版和英文版 学习java怎么能缺少API帮助文档呢?经过我的不断搜寻,jdk1.8的中文版和英文版都给你们整理好了,不用谢,喜欢就关注我,我们一起学习。 jdk1.8中文版 提取码: iih6 jdk1.8英文版 提取码: an15 大家好,我是LA,萌新一枚,平常主要写一些基础知识加深自己的印象,能和大家分享我也很高兴.我会尽力写一些能帮助到大家的文章,如果文章中有错误的地方...

weixin_44692666的博客 8509

空间索引 S2 学习指南及Java工具类实践

原先公司使用相对主流的geohash生成空间索引进行区域查询,后来发现geohash对于大区域查询表现极不良好,经调研测试,改用google的s2。因为涉及的资料、工具较多,特此记录,以备后用。 文章目录一 学习指南0 介绍说明1 s2 对比 geohash 的优点2 相关资料二 Java实践 一 学习指南 0 介绍说明 班门不弄斧,这里推荐 halfrost 大神的空间搜索系列文章,推荐先浏...

且炼时光 3661

Java 开发者 Linux 学习指南

本文详细介绍了Java开发者为何必须掌握Linux,并提供了从Linux基础到Java应用部署的全面指南。文章首先强调了Linux在Java应用部署中的重要性,随后深入讲解了Linux的核心概念、常用命令、Java环境安装与配置、开发与构建工具、JVM性能优化与监控、应用部署与容器化、日志分析与自动化运维、安全配置与最佳实践等内容。通过实战案例,展示了如何在Linux上部署Spring Boot应用。最后,文章总结了学习资源,鼓励开发者通过持续学习和实践,提升在Linux与Java领域的专业技能。

m0_71744084的博客 3397

java-guide:现代Java学习指南

在Java不断进化的历程中,始终有一份学习者的需求——如何从基础到进阶,系统地掌握这门语言。java-guide项目正是为了满足这样的需求而诞生。它是一份针对现代Java(Java 17)的指南,旨在帮助那些有一定C语言或JavaScript基础的读者,从零开始学习Java。该项目是一个持续更新的作品,预计将在Java下一个长期支持版本(Java 17)发布时完成。 ## 项目技术分析 jav

gitblog_00502的博客 847
上一篇: Overriding与Overloading
下一篇: Web服务器与应用服务器
andyjava2006
博客等级 码龄20年 1粉丝 9原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值