The example of this article summarizes the Java central thread usage method. Share it for everyone for your reference. The specific analysis is as follows:
1. The thread is the basic scheduling unit. The resources of the shared process, such as memory and file handles. But with your own PC (program counter), Stack (thread stack) and local variables
2. The advantages of thread:
a) Make full use of multiple processors
b) Can simplify the model. Specific tasks are given to specific threads. Such as Servlets and RMI and other frameworks.
c) Simple treatment of asynchronous events. Such as Socket, NIO is more complicated. The current operating system supports a larger number of threads.
d) better response of the interface
3. Internal lock: Synchronized block. Mutual. Reunar), such a design can avoid dead locks
4. Memory visibility: Because of the optimization of the compiler, the thread is not the same as what you see.
Public Class Novisibility {Private Static Boolean Ready; Private Static Int Number; Private Static Class Readerads Threads Thread Run (). {While (! Ready) Thread.yield (); System.out.println (Number);}} public static void main (string [] args) {new readrthread (). Start (); number = 42; ready = true;}}
May print 0, or keep circulating. Because it is sorted
5. Volatile: It can solve the visibility of memory and has a better performance for Syncronized, but that is nothing more than that, if you cannot guarantee the atomicity of A ++
6. Escape: Do not overflow the THIS pointer in the constructor. Do not overflow the internal variables, such as:
class test {Private String [] list = New String [] {}; Public String [] getlist () {Return list;}}}
7. Threads closed: Closing the object in one thread, whether the object is safe or not, can ensure that thread is safe
a) STATCK limit. That is, only local variables can access the object.
b) ThreadLocal.
8. Unchanged objects. It must be thread safe. Unsatisfactory objects must be satisfied:
a) The state cannot be modified after creation.
b) So the domain is full
c) Create the object correctly, without the THIS pointer overflow
9. Publish safely
a) initialization object through static
b) Use Volatile or AtomicReference
c) The Final domain of the correctly created object is stored in
d) Use locks
It is hoped that this article is helpful to everyone's Java program design.