Java multi-threading (1) - Basic Concepts

First, the basic concept

Process (Process) : running instance of the program. The relationship between the processes and procedures like video and corresponding video file playback ratio. Process is a program to apply the basic unit of the operating system resources (such as memory and file handles) are.
Thread (the Thread) : the smallest unit of independently executable process. A process can contain multiple threads share the process resources with all threads in a process. A thread Java platform is an object.
Tasks (Task) : computing threads to be accomplished.
Serial (Sequential) : complete sequence one by one.
Concurrent (Concurrent) : the same period alternately to complete.
Parallel (Parallel) : the same time begin to complete. Stricter concurrency.

Second, create a startup thread running

Java to create a thread is to create an java.lang.Threadinstance of the class. Task processing logical thread may be in the Threadclass runexample implementation process. It is called directly by the virtual machine when running the corresponding thread, rather than by the application code calls.

ThreadClass startmethod of action is to start the corresponding thread. The substance is a request to start a thread corresponding virtual machine running thread, and this thread is exactly when to run is determined by the thread scheduler (scheduler) of. Therefore, startthe method call does not mean the end of the thread is already running, this thread might run was only later, and even may never be run.

Thread runmethod has finished executing, the corresponding thread end of the run. Thread startmethod can be called only once, that is, thread one-time items.

//Thread两个常用构造器
public class Thread implements Runnable {
    public Thread() {
        init(null,null,"Thread-"+nextThreadNum(),0);
    }

    public Thread(Runnabletarget) {
        init(null,target,"Thread-"+nextThreadNum(),0);
    }

    /**
     * Initializes a Thread.
     *
     * @param g the Thread group
     * @param target the object whose run() method gets called
     * @param name the name of the new Thread
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     * @param acc the AccessControlContext to inherit, or
     *            AccessController.getContext() if null
     * @param inheritThreadLocals if {@code true}, inherit initial values for
     *            inheritable thread-locals from the constructing thread
     */
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
        //...
    }
}

Virtual machine allocated for each thread call stack (callstack) required memory space, Java platform, each thread there may be a kernel thread corresponding, therefore, to create a thread object creation cost than other types of objects to be higher some.

Third, the thread property

Attributes Types of use Remark
ID Number long Identify different threads. After a certain number of threads running, the number of threads may be created subsequent use. Unique number is only valid in one run Java virtual machine. Thus the value of this attribute is not suitable for some unique identifier (e.g., primary key)
Name Name String For people attribute to distinguish different threads. The default isThread-ID Set the name of the thread property code debugging and help locate the problem
Daemon thread category boolean Is a daemon threads. By default the same as the parent thread The property must be set before the corresponding thread is started. Responsible for mission-critical processing threads inappropriate to set a daemon thread
Priority Priority int Java defines a priority of 10 to 10. The default value is generally 5 (normal priority). For a particular thread, its default priority value equal to the priority value of the parent thread. Generally you can use the default priority.

Depending on whether Java virtual machine thread prevents normal stop, we can in Java thread into a daemon thread (DaemonThread) and user thread (UserThread, also known as non-daemon threads) .
Users thread prevents normal stop Java virtual machine, namely a Java virtual machine can only be stopped in the case of all of its normal user threads run ended.
The daemon threads will not affect the normal stopping the Java virtual machine that is running a daemon thread does not affect the normal stopping the Java virtual machine applications.
Therefore, the daemon thread is usually used to perform some of the tasks is not very high importance, for example, for monitoring the operation of the other threads.

Four, Thread class

method Features Remark
static Thread currentThread() Returns the current thread
void run() Character processing logic to implement threads Applications should not call general
void start() Start the corresponding thread It can only be called once
void join() Waiting for the end of the corresponding thread running A calls B, joinMethod A suspended until the end of the operation B
static void yield() The current thread give up its occupation of the processor, may cause the current thread is suspended The method is not reliable
static void sleep(long millis) Sleep specified time

Fifth, thread life cycle

Since the main thread (the main thread) Java virtual machines created a Java program responsible for implementing the method of entry mainmethod.

Life cycle between parent and child thread thread does not necessarily linked.

  • NEW: not started a thread has been created in the state. Since a thread instance can be activated only once, so there can be only once a thread is in this state.
  • RUNNABLE: This state may be viewed as a composite state. It includes two sub-states: READY and RUNNING.
    READY state indicates that the thread is a thread scheduler can be performed so that the scheduling in the RUNNING state. Thread in this state for the active thread.
    RUNNING state indicates that the thread is running, i.e., the corresponding thread object runmethod corresponding to the instruction is being executed by a processor.
  • BLOCKED: blocking a thread initiates a rear I / O (BlockingI / O) operations, or to apply a monopoly held by another thread resources (such as locks), the corresponding thread in this state. Thread in this state does not occupy processor resources.
  • WAITING: This will be in waiting for the other thread to perform some additional specific operating state after a thread to perform a certain method. Such Object.wait()as: , Thread.join()and LockSupport.park(Object). The corresponding thread can change from WAITING to RUNNABLE appropriate method comprising: Object.notify()/notifyAll()and LockSupport.unpark(Object)).
  • TIMED_WAITING: The WAITING state and similar, the difference is that the thread is in this state is not indefinitely wait for another thread to perform a particular operation, but in a wait state with time constraints. Other thread when the thread does not perform a specific operation is desired within a specified time, the state of the thread is automatically converted to RUNNABLE.
  • TERMINATED: end of the thread has been performed in this state. A thread may have only once in this state. Thread.run()Normal return or throw an exception due to the early termination will result in a corresponding thread is in this state.





Shenkaoziliao: "Java multi-threaded programming practical guide (core papers)" with Huang Wenhai

Guess you like

Origin www.cnblogs.com/JL916/p/12309733.html