About Java threads

Source: Internet
Author: User

Generally, the Java code we write runs in the form of a process. The written code is a "program", and the executed program is a "process ". A process is an independent unit for the system to allocate and schedule resources.

A thread is located at the lower level of a process and the smallest Execution Unit in the system. But the thread itself does not have resources, and the thread itself generally only has register data and the stack during execution. Multiple threads in the same process share resources of the current process and must be preemptible when resources are required.

The purpose of multi-threaded programming is to allow the program to use resources such as CPU to the maximum extent. when processing a thread does not need to occupy the CPU but only deals with resources such as I/O, this gives other threads that need to occupy CPU resources the opportunity to obtain CPU resources. Compared with inter-process communication, inter-thread communication consumes less resources and makes it easier to implement. In addition, it can make full use of the free time of the CPU, which is also the purpose of multi-thread programming.

2. Thread Scheduling and State 2.1 Thread Scheduling

Because a thread is the basic unit for System Scheduling and task execution, there is at least one default thread for a process. This thread is usually called the main thread. CPU is required for thread execution. The CPU slices its own time and then provides external services in units of time slices. For example, if there are 50 slices per unit time and the current thread has A, B, and C, then the possible result is to give A several time slices, B several time slices, and C Several time slices, on the surface, in a unit of time, all threads are executed simultaneously. However, for a single CPU (single core), there is a sequential serial execution. The scheduling mode of this thread is determined by the operating system.

Currently, there are two main scheduling methods:

(1) Non-preemptible mode: Once a thread is selected to run on the CPU, it will continue to run until it is blocked or automatically exits. In this way, the entire system may be suspended.

(2) preemption: A thread is selected to run on the CPU, and the allowed running time is limited. The system may hand over the CPU to other threads for execution, it is completed by clock interruption. Currently, preemptible scheduling algorithms include first-come-first-served algorithms, time slice scheduling algorithms, and priority scheduling algorithms.

Status of 2.2 threads

With the above thread scheduling, we will naturally mention the state of the thread in different periods.

There are generally five types of thread states: new state, ready state, running state, blocking state, and death state. However, in terms of extension, adding the lock status can better understand the thread.

 

According to the JDK explanation, the thread status is divided into six types:

(1) NEW: the thread has just been created but has not been started;

(2) RUNNABLE: the status of the thread running in JVM. It may be in the waiting status due to the lack of CPU and other resources;

(3) BLOCKED: Blocking status, waiting for other threads to release the synchronization lock or IO;

(4) WAITING: After the thread calls the wait method (No parameter), join method (No parameter), and LockSupport. park method, it enters the WAITING status and waits for it to be awakened;

(5) TIMED_WAITING: When the thread calls the sleep method, wait method (with parameters), join method (with parameters), LockSupport. parkNanos, LockSupport. parkUntil;

(6) TERMINATED: end the execution;

When the code is running on linux, you can use the jstack command to view the status of all threads in the current process, that is, the above six.

3. Thread implementation

This article is intended for Java. For Java, there are two ways to implement threads. One is that the current class inherits the Thread class, and the other is to implement the Runnable interface.

3.1 inherit the Thread method

In this way, you only need the current extends Thread class and then implement the run () method. Therefore, in the class constructor, it will inevitably involve the super class Thread construction.

Thread is also the default Runnable interface:

  Thread  Runnable

 

3.1.1 Thread construction without Parameters

The Thread has an init method to initialize Thread-related information, such as the Thread name, the Thread group, and the size of the allocated Thread stack.

   init(ThreadGroup g, Runnable target, String name,  stackSize) 

, , "Thread-" + nextThreadNum(), 0

        threadInitNumber++

3.1.2 Thread construction with Parameters

Let's take a look at the Thread construction with parameters.

There are a total of seven parameter cases, in fact, that is, to selectively assign values to parameters in the init method.

   init(ThreadGroup g, Runnable target, String name,== (g ==              (security != =        (g == =

(security != g.addUnstarted(); .group =.daemon =.priority =.name = (security == ||.contextClassLoader = .contextClassLoader =.inheritedAccessControlContext =.target = (parent.inheritableThreadLocals != .inheritableThreadLocals = .stackSize = =
}

The method for implementing the Runnable interface is equivalent to inheriting the Thread class above. Runnable is an interface, and the current class can implement multiple interfaces. However, if it is inherited, it is hard to hurt, java does not allow many inheritance, which makes it easier to implement Runnable in practical applications.

Just like the above Thread class, implementing the Runnable interface is actually to implement the run method. In fact, this interface also has only such a run method.

4. common thread Methods

There are several common methods when using a thread. Let's make a summary of these common methods: start (), run (), wait (), notify (), policyall (), sleep (), join (), interrupt (), yield (), suspend (), setDaemon ().

4.1 start Method

A thread starts from start. The source code is as follows:

    (threadStatus != 0 

4.2 run Method

We usually need to reload this method to complete the functions we need, because the native run method has nothing to say.

   (target != 

This method was originally a self-owned method in Java's top-level parent class Object, used to wake up a thread waiting for the Object lock. If there are multiple threads waiting, a random wake-up will be selected. The method to wait for the object lock is implemented through the wait method.

However, the wake-up thread cannot be immediately executed to the state when the current thread abandons its object lock. The wake-up thread will compete with other queued threads again.

By the way, a thread can obtain the object lock in three ways:

(1) execute the synchronized instance method of the Object;

(2) execute the synchronized code block;

(3) through the static synchronized Method of the class;

4.4 notifyAll Method

Like the other y method above, the notifyAll method is used to wake up a thread waiting for the object lock. The difference is that the yyall method is to wake up all threads in the waiting state. It should be noted that when the number of threads increases, the time consumed by this method will also increase because of the heavy workload.

4.5 sleep method

This means that the current thread is stuck, that is, BLOCKED. However, even in a "dream", this thread will not discard the acquired object lock. The unit of sleep time is ms.

4.6 join method

The join method can have parameters or no parameters. In essence, the wait method is called. The following describes the wait method. Let's take a look at the join method of a parameter.

 

      join( base = now = 0 (millis < 0  IllegalArgumentException("timeout value is negative" (millis == 00 delay = millis -                  (delay <= 0                    = System.currentTimeMillis() -

4.7 interrupt method

Interrupt the execution of the current thread. After the current thread calls this method:

(1) If the thread is in a resumable state (wait, sleep, join, Selector is called. select method), the thread will be immediately awakened, and an InterruptedException will be received. If it is blocked on io, the corresponding resource will be closed and ClosedByInterruptedException will be received.

(2) If the current thread is in an uninterrupted state, Java only sets the thread's interrupt state. If you continue to call the blocking function later, InterruptedException will be thrown, if the blocking method is not used, the thread continues to execute. After the interrupt method is called, the program continues to execute. This is the reason for this situation.

Now we know how to properly interrupt a thread. There are three ways to handle it:

(1) Call Thread. interrupted () to determine whether the Thread has been interrupted;

(2) Capture InterruptedException exceptions;

(3) combination of the above two methods;

4.8 yield Method

Pause the execution of the current thread. The current thread exits from the running status and enters the running status. The lock is not released.

This method is similar to sleep. it suspends the current execution and does not release the lock. The difference is that the current thread will not be executed during the specified time of the sleep thread, yield may be executed again immediately, and sleep can lead to execution of low-priority threads. yield can only give threads with the same priority a chance to execute.

4.9 suspend Method

This method is no longer recommended. This function enables the current thread to directly enter the blocking state and will not be automatically restored. You must call the resume method to restore the thread. But it may cause deadlocks.

4.10 wait Method

The wait method here is actually a self-owned method of the Object class. When this method is executed, the system enters a waiting pool related to the current object and releases the lock. The waiting thread continues to run until another thread calls the notify or yyall method of the current object. Wait must be used in the synchronized code block and can only be called by the thread of the owner of the current object lock. After the restoration is executed, the next statement from wait continues to be executed. Therefore, the wait method is always called in the while method.

The wait method can also be divided into two forms: parameter and parameter-free.

(1) parameter format: the input parameter is the length of time to wait. In this case, in addition to being awakened by the Y and notifyAll methods, the current thread will be automatically rejoined to the lock competition after the specified wait time is reached.

(2) No parameter format: in fact, the wait method with parameters is also called, but the time value is set to the default 0.

4.11 setDaemon Method

Used to set whether the current thread is a daemon thread or a common user thread. If it is a daemon thread, this method must be called before the thread is started.

In fact, the daemon thread refers to the thread used to serve the user thread. If no other user thread is running, there will be no service-able objects and the thread will exit. For example, the garbage collection thread is a typical daemon thread.

If a subthread is created in a daemon thread, these subthreads are also daemon threads by default.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.