Register, stack, heap, static storage, constant storage (constant pool String a = "abc" a is in the stack, "abc" is in the constant pool), non-RAMstorage
As a member of the class, it is automatically initialized to the default value
boolean 1bit Defaultfalse
byte 8bits One byte \u0000
char 16bits One character 0
short 16bits 0
int 32bits 0
float 32bits 0.0f
long 64bits 0L
double 64bits 0.0d
BigInteger, Bigdecimal High precision, slow speed
Java has a special "garbage collector" that looks for all objects created with new and identifies which of them are no longer referenced . It then automatically frees the memory occupied by those idle objects so that it can be used by new objects.
Parent class static Member variablesand static Statements
static Member variables and# of subclasses ## static Statement
Parent class non- static member variable and are not static Statement block
Construction method of parent class
Non- static member variables and non-static statement blocks of subclasses
Construction method of subclass
(static is only executed once. The first time Executed when new)
Vector
An array that will grow automatically, with high query efficiency, low addition and deletion efficiency, thread safety, slow speed, and double the original size.
ArrayListwill automatically grow the array, with high query efficiency, low addition and deletion efficiency, thread unsafe, fast speed, and will grow to the original 0.5 times.
LinkedListBidirectional circular linked list has low query efficiency, high addition and deletion efficiency, and is thread-unsafe.
HashMapis a linked list hash, which is a combination of an array and a linked list. It allows null values, is thread-safe and highly efficient.
TreeMapis implemented for binary sorting tree, using Key for sorting.
LinkedHashMapis implemented for hash tables and linked lists. It is a subclass of HashMap. It retains the order of insertion. If output is required The order is the same as the input, then use LinkedHashMap.
Hashtable Thread safe, low efficiency, null value is not allowed.
Set is non-repeatable:
TreeSet is implemented based on TreeMap and is ordered Yes, thread-unsafe.
HashSet Based on HashMap implementation, HashMap#key .
LinkedHashSet is implemented based on LinkedHashMap and is ordered.
##Use entrySet Traversal Map class collection KV, instead of keySet way to traverse. 1, entrySet implements the Set interface, which stores key-value pairs. A K corresponds to a V. Bridge stream: InputStreamReader Convert byte stream into character stream. (Read as converted into a character stream) Convert the character stream into a byte stream (Write as converted into a byte stream) InputStream OutputStream Reader Writer FileInputStream FileOutStream FileReader
Buffered Stream BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
DataInputStream DataOutputStream 1.Java IO adopts the decoration mode, which uses the processing stream to wrap the node stream to achieve code versatility. 2.How to distinguish between processing flow and node flow. Node flow requires a data source (file, network) as a parameter when creating a new one, while processing flow requires a node flow as a parameter. 3.The function of processing flow is to improve the versatility of code, the convenience of writing code, and improve performance. 4.Node streams are all implementation classes corresponding to the abstract base class, and they all implement the basic reading and writing methods of the abstract base class. Among them, if the read() method returns -1, it means that the end of the data source has been read. 1. Frame diagram of the input stream in bytes The following is a frame diagram of the input stream in bytes. From this, we can see. The following is the frame of the output stream in bytes picture. From this, we can see. The common parent class for output streams in bytes is OutputStream.
Threads include the following 5 states. InheritanceThread implementationRunnable mythread.start() will start a new thread and run the run() method in the new thread. We summarize the basic rules of synchronized as follows3 articles and illustrate them with examples. notify()-- Wake up and wait on this object monitor of a single thread. yield()’s function is to yield. It allows the current thread to enter from "Running state" to "Ready Status ”, thereby allowing other waiting threads with the same priority to obtain execution rights; however, there is no guarantee that yield() will be called on the current thread. After that, other threads with the same priority will definitely be able to obtain execution rights; it is also possible that the current thread has entered "Running state"Keep running! sleep() Defined in Thread.java middle. We know that the function of wait() is to make the current thread change from "Running state”Enter”Waiting(Blocking)State”, the synchronization lock will also be released. The function of sleep() is also to make the current thread change from "Running state"Enter"sleep(blocking)state”. We know that the function of wait() is to make the current thread enter ## from "Running state" #"Waiting(Blocking)Status" At the same time, the synchronization lock will also be released. The function of yield() is to give way, it will also make the current thread leave "Running state" . The difference between them is: (01) wait() Defined in Thread.java middle. join() Main threadpublic class Father extends Thread { Son threadpublic class Son extends Thread { The function is to interrupt this thread. This thread is allowed to interrupt itself; when other threads call this thread's interrupt() method, they will pass checkAccess() Check permissions. This may throw a SecurityException exception. If this thread is in a blocked state: call the thread's wait(), wait(long) or wait(long, int) It will enter the waiting (blocking) state, or call the thread's join(), join( long), join(long, int), sleep(long), sleep(long, int) will also put it into a blocking state. If the thread calls its interrupt() method when it is in the blocked state, then its "interrupt state” will be cleared and an InterruptedException exception will be received. For example, the thread enters the blocking state through wait(), and then interrupts the thread through interrupt(); call interrupt() will immediately set the thread's interrupt flag to "true", but because the thread is blocked, this"Interrupt flag" will be cleared immediately to "false", and at the same time, a # will be generated ##InterruptedException exception. If a thread is blocked in a Selector selector, then when it is interrupted by interrupt(); The thread's interrupt flag will be set to true, and it will return immediately from the select operation. If it does not fall into the above situation, then when the thread is interrupted through interrupt(), its interrupt mark will be set to "true". Interrupting a "terminated thread" will result in no action. Usually, we pass"Interrupt" way to terminate the thread in "blocked state". Usually, we pass"mark " way to terminate the thread in "Running state". Among them, include "Interruption mark" and "Additional addition mark”. @Overridepublic void run() { while (!isInterrupted()) { // Execute tasks... } } Explanation: isInterrupted() is to determine the interruption of the thread Is the tag true. When a thread is running and we need to terminate it; we can call the thread's interrupt() method, using the thread's interrupt flag as true , that is, isInterrupted() will return true. At this point, the while loop will exit. (02) Add additional tags by "". private volatile boolean flag= true;protected void stopTask() { flag = false; } @Overridepublic void run() { while (flag) { // Execute task ... } } Explanation: There is a flag tag in the thread, and its default value is true ; And we provide stopTask() to set the flag tag. When we need to terminate the thread, calling the thread's stopTask() method will allow the thread to exit the while loop. Finally talk about interrupted() and isInterrupted(). Every thread has a priority. "High priority threads" will take precedence over "low priority threads "implement. Each thread can be marked as a daemon or non-daemon. When a new child thread is created within some running main thread, the child thread's priority is set equal to the priority of the main thread that created it. ", if and only if"The main thread that created it is a daemon thread" "The child thread will be the daemon thread". When the Java method startup). JVM will continue to run until any of the following conditions occurs, JVM will terminate: (01) The exit() exit() has permission to be executed normally. (02) All" "are dead(That is, there are only "daemon threads in JVM ”). Each thread is marked as " or "User Thread". When only the daemon thread is running, JVM will automatically exit.
Explanation: keySet is actually traversed 2 times, and once it is converted to Iterator object, the other time is to take out the value## corresponding to key from
hashMap #. And entrySet only traversed once and put both key and value entry , the efficiency is higher. If it is
JDK8, use the Map.foreach method. Positive example:
values() returns a V value set, which is a list Collection object; keySet() returns the K value set, which is A
Set Set object; entrySet() returns a K-V value combination set.
2, a method used to traverse map.
Set
for (Map.Entry
System.out .println(entry.getKey()+","+entry.getValue());
}
GetK## through getKey() #,getValuegetV.
3
, and another one is keySet. Set
for (String s:set) {
System.out.println(s+","+map.get(s)) ;
}2. IOSystem
Traffic classification
Use classification
Byte input stream
Byte output stream
Character input stream
Character output stream
Abstract base class
Node Stream
Access File
##FileWriter
Access value
ByteArrayInputStream
ByteArrayOutStream
CharArrayReader
CharArrayWriter
Access pipe (thread interaction)
PipedInputStream
PipedOutStream
PipedReader
PipedWriter
Access string
StringReader ##StringWriter ##Processing Stream
##Convert stream
InputStreamReader
OutputStreamWriter
Object Stream
ObjectInputStream
ObjectOutputStream
##Abstract base class (filtering) Print Stream ##FilterInputStream
FilterOutputStream
FilterReader
FilterWriter
Pushback InputStream
PrintStream
PrintWriter
PushbackInputStream
PushbackReader
##Special Stream
(01) InputStream is the superclass of input stream in bytes. InputStream Provides the read() interface to read byte data from the input stream.
(02) ByteArrayInputStream is a byte array input stream. It contains an internal buffer that contains the bytes read from the stream; in layman's terms, its internal buffer is a byte array, and ByteArrayInputStreamessentially This is achieved through byte arrays.
(03) PipedInputStream is a pipeline input stream. It is used together with PipedOutputStream to achieve pipeline communication between multiple threads.
(04) FilterInputStream is to filter the input stream. It is the superclass of DataInputStream and BufferedInputStream.
(05) DataInputStream is the data input stream. It is used to decorate other input streams, which "allows applications to read basic Java data types from the underlying input stream in a machine-independent manner."
(06) BufferedInputStream is a buffered input stream. What it does is add buffering functionality to another input stream.
(07) File is an abstract representation of "file" and "directory path name". Regarding File, please note two points:
a), File not only represents a file, it can also represent a directory!
b), FileAlthough it is defined carefully in io, its super class is Object , instead of InputStream.
(08) FileDescriptor is the "file descriptor". It can be used to represent open files, open sockets, etc.
(09) FileInputStream is the file input stream. It is usually used for reading operations on files.
(10) ObjectInputStream is the object input stream. It, together with ObjectOutputStream, is used to provide persistent storage of "basic data or objects".
2. Frame diagram of the output stream in bytes
(01) OutputStream is the superclass of the output stream in bytes. OutputStream Provides the write() interface to read byte data from the output stream.
(02) ByteArrayOutputStream is a byte array output stream. Data written to ByteArrayOutputStream is written to a byte array. The buffer will grow automatically as data is continuously written. Data can be obtained using toByteArray() and toString() .
(03) PipedOutputStream is a pipeline output stream. It is used together with PipedInputStream to realize pipeline communication between multiple threads.
(04) FilterOutputStream is the filter output stream. It is a superclass of DataOutputStream, BufferedOutputStream, and PrintStream.
(05) DataOutputStream is the data output stream. It is used to decorate other output streams, which "allows applications to write to the underlying Java data types in a machine-independent manner."
(06) BufferedOutputStream is a buffered output stream. What it does is add buffering functionality to another output stream.
(07) PrintStream is the print output stream. It is used to decorate other output streams and add functionality to other output streams so that they can easily print various data value representations.
(08) FileOutputStream is the file output stream. It is typically used for writing to files.
(09) ObjectOutputStream is the object output stream. It, together with ObjectInputStream, is used to provide persistent storage of "basic data or objects". 3. Multi-threading
Life cycle
1. New state(New): After the thread object is created, it enters the new state. For example, Thread thread = new Thread().
2. Ready state(Runnable): Also known as "executable state". After the thread object is created, other threads call the start() method of the object to start the thread. For example, thread.start(). Threads in the ready state may be scheduled for execution by CPU at any time.
3. Running status(Running): The thread obtains CPU permission to execute. It should be noted that a thread can only enter the running state from the ready state.
4. Blocked state(Blocked) : The blocked state is when the thread gives up for some reasonCPURight to use, temporarily stopped running. Until the thread enters the ready state, it has a chance to move to the running state. There are three blocking situations:
(01) Waiting for blocking-- By calling the thread's wait()Method to let the thread wait for the completion of a certain job.
(02) Synchronization blocking-- The thread failed to acquire the synchronizedsynchronization lock (Because the lock is occupied by other threads), it will enter the synchronous blocking state.
(03) Other blocking-- By calling the thread's sleep() or ## When #join() or an I/O request is issued, the thread will enter the blocking state. When sleep() status times out, join() waits for the thread to terminate or times out, or I/O When the processing is completed, the thread returns to the ready state. 5.
Death state(Dead) : The thread has finished executing or exited due to an exceptionrun()Method, the thread ends its life cycle. start() and run() Description of the difference
//
And mythread.run() will run the run() method directly in the current thread and will not start A new thread to run run().
3.synchronized
First Article: When a thread accesses "Some object""synchronizedmethod"or"synchronizedcode block ", other threads are interested in "this object"'s "synchronizedmethod"or"synchronizedcode block" Access to will be blocked.
Second Article: When a thread accesses "Some object""synchronizedmethod"or"synchronizedcode block ", other threads can still access the asynchronous code block of "this object" .
Article 3: When a thread accesses "Some object""synchronizedmethod"or"synchronizedcode block ", other threads "this object"'s other "synchronizedmethod"or"synchronizedcode block"## Access to # will be blocked.
4.wait(), notify(), notifyAll()
notifyAll()-- Wake up all threads waiting on this object monitor.
wait()-- Let the current thread be in "Waiting(Blocking)State","until other threads call this object's notify() method or notifyAll() method”, the current thread is awakened(Enter"Ready state").
wait(long timeout)-- Let the current thread be in "Waiting(Blocking)State","until other threads call this object's notify() method or notifyAll() method, or the specified amount of time ”, The current thread is awakened(Enter"Ready state").
wait(long timeout, int nanos)-- Let the current thread be in “wait( Blocking)State"," until another thread calls this object's notify() method or notifyAll() method, or some other thread interrupts the current thread, or a certain actual amount of time has elapsed ", the current thread is awakened(enters "ready state ”). 5.yield()Introduction
6.sleep()Introduction
sleep() The function is to make the current thread sleep, that is, the current thread will enter from "Running state" ##"Hibernate(Blocking)State". sleep() will specify the sleep time, and the thread sleep time will be greater than / equal to the sleep time; when the thread is awakened again , it will change from "Blocking State" to "Ready State" , thus waiting for the scheduled execution of cpu.
However, wait() will release the synchronization lock of the object, while sleep() will not release the lock.
The following example demonstrates that sleep() will not release the lock.
Let the thread change from "Running state"Enter "Waiting(Blocking)State”, and yield() causes the thread to change from ” to the running state”Enter ”Ready state”. (02) wait()
will cause the thread to release the synchronization lock of the object it holds, but the yield() method will not release the lock. join()Introduction
join()
Function: Let"main thread"wait"child thread" can only continue to run after it ends. This sentence may be a bit obscure, but we still understand it through examples: interrupt() and the way to terminate the thread
interrupt()8.1 Terminate the thread in the "blocked state"
When the thread enters the blocking state due to being called sleep(), wait(), join() and other methods; if the thread's ## is called at this time #interrupt()Set the thread's interrupt flag to true. Due to the blocking state, the interrupt mark will be cleared and an InterruptedException exception will be generated. Put InterruptedException until appropriate to terminate the thread
8.2 Terminate the thread in the "running state"
(01) Terminate the thread by "Interrupt Flag".
The form is as follows:
Note: interrupt() will not terminate the "running state" the rout! It will set the thread's interrupt flag to true.
The form is as follows:
Note: flag is defined as volatile type to ensure flag visibility. That is, after other threads modify flag through stopTask(), this thread can see the modified The value of flag.
interrupted() and isInterrupted() can both be used to detect the object’s “interrupt flag ”.
The difference is that interrupted()In addition to returning the interrupt mark, it will also clear the interrupt mark(The upcoming interrupt mark Set to false); and isInterrupted() only returns the interrupt flag
9.Thread priority and daemon thread
The above is the detailed content of Share some basic Java interview questions. For more information, please follow other related articles on the PHP Chinese website!