The example of this article summarizes the Java thread usage. Share to everyone for your reference. The specific analysis is as follows:
1. Threads are basic dispatch units. A resource for sharing processes, such as memory and file handles. But has its own PC (program counter), stack (line stacks) and local variables
2. Advantages of threading:
(a) Full utilization of multiprocessor
b) can simplify the model. Specific tasks to specific threads. such as Servlets and RMI and other frameworks.
c) Simple processing of asynchronous events. such as Socket,nio is more complex to use. And now the operating system supports a larger number of threads.
D) Better response to the interface
3. Internal lock: synchronized block. Mutually exclusive. Reentrant (reentrancy), designed to avoid deadlocks
4. Memory Visibility: Because of compiler optimizations, threads are not what you see.
public class Novisibility {
private static Boolean ready;
private static int number;
private static class Readerthread extends Thread {public
void run () {while
(!ready)
Thread.yield ();
SYSTEM.OUT.PRINTLN (number);
}
public static void Main (string[] args) {
new Readerthread (). Start ();
Number = N;
Ready=true
}
}
May print 0, or keep looping. Because of the reordering
5.volatile: Can resolve memory visibility, better for syncronized performance, but only this, such as not guarantee the atomic nature of a++
6. Overflow (escape): Do not overflow the this pointer in the constructor. Do not overflow internal variables, such as:
Class Test {
private string[] list = new string[] {};
Public string[] GetList () {return list;}
}
7. Thread closure: The object is closed in a thread, regardless of whether the object is thread safe, can ensure thread safety
A) Statck restrictions. That is, only local variables can access the object.
b) ThreadLocal.
8. Immutable objects. Must be thread-safe. Immutable objects must be satisfied:
A The status cannot be modified after creation.
b) So the domain is final
c) Correctly create object without this pointer overflow
9. Security release
A The object is initialized by static
b) Use of volatile or atomicreference
c The final domain that will be stored in the correctly created object
d) Use of locks
I hope this article will help you with your Java programming.