Summary of thread usage in Java

  • 2020-04-01 03:55:37
  • OfStack

This example summarizes thread usage in Java. Share with you for your reference. Specific analysis is as follows:

1. Threads are the basic scheduling unit. Shared process resources, such as memory and file handles. But it has its own PC (program counter), stack(thread stack), and local variables

2. Advantages of threads:

A) make full use of multiple processors
B) the model can be simplified. Specific tasks to specific threads. Frameworks such as servlets and rmi.
C) simple handling of asynchronous events. Like socket, nio is more complex to use. Today's operating systems support a much larger number of threads.
D) better response of the interface

3. Internal locks: synchronized blocks. The mutex. Reentrancy, a design that avoids 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 = 42;
 ready=true;
}
}

It might print a 0, or it might loop through. Because it's reordered

5. Volatile: memory visibility can be resolved and syncronized better, but that's about it, for example, atomicity of a++ cannot be guaranteed

Overflow (escape) : do not overflow 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 closure of an object in a thread, whether the object is thread-safe or not, can ensure thread safety

A) statck restrictions. That is, only local variables can access the object.
B) a ThreadLocal.

8. Immutable objects. It must be thread safe. Immutable objects must satisfy:

A) the state cannot be changed after creation.
B) all fields are final
C) create the object correctly without this pointer overflow

9. Secure release

A) initialize an object with static
B) use volatile or AtomicReference
C) store the reference in the final field of the correctly created object
D) using a lock

I hope this article has been helpful to your Java programming.


Related articles: