Java Multithreading Summary (i) Multithreading basics

Source: Internet
Author: User
Tags instance method cpu usage java web

This article reproduces the address:

Http://www.cnblogs.com/zrtqsk/p/3776328.html

Multithreading is a very important aspect of Java learning and a basic skill that every Java programmer must master. This article is just multithreading details, the essence of the summary, and no code examples to get started, not suitable for beginners to understand. Beginners Learn multi-threading, it is recommended to read books, read blog, in order to write code to try.

First, the process

  A process is the basis of the structure of an operating system; It is the execution of a program; the activity that occurs when a program and its data are executed sequentially on the processing machine. In the operating system, almost all running tasks correspond to a process. A program goes into memory to run, which becomes a process. A process is a program that is in the process of running and has some independent functionality. A word describing the process is very classic-a process is an independent unit of system resource allocation and scheduling.

A process is an entity that exists independently in the system, has its own independent resources, and has its own private address space . the essence of the process is the process of executing a program in a multi-channel program system, which is generated dynamically, and has its own life cycle and various states. The process is concurrency and can be executed concurrently with other processes, moving forward at their own, unpredictable speed .

(Note that concurrency (concurrency) and parallelism (parallel) are different.) Parallelism refers to the same moment when multiple instructions run concurrently on multiple processors. Concurrency refers to the execution of only one instruction at a time, but multiple process instructions are executed quickly, seemingly as if multiple instructions were executed concurrently. )

Process consists of three parts: program , data and Process Control block .

Second, the thread

A thread, sometimes called a lightweight process (lightweight PROCESS,LWP), is the smallest unit of program execution flow. A standard thread consists of a thread ID, a current instruction pointer (PC), a collection of registers, and a stack. In addition, the thread is an entity in the process, is the basic unit that is dispatched and dispatched by the system independently, the thread does not own the system resources, only has a bit of resources that are essential in the operation, but it can share all the resources owned by the process with other threads belonging to one process . One thread can create and revoke another thread, which can be executed concurrently between multiple threads in the same process. Because of the mutual constraints between threads, the thread is running in a discontinuous. Each program has at least one thread, and if the program has only one thread, it is the program itself.

   a thread is a single sequential control flow in a program. Run multiple threads at the same time in a single program to do different work, called multithreading。

in the Java Web, it is important to note that threads are JVM-level and perish with the JVM without stopping, that is, if a Web service launches multiple Web applications, a Web application launches a thread, and if the Web application is closed, the thread does not close. Because the JVM is still running, don't forget to set the stop thread when the Web app shuts down.

Third, thread state

(Image source: http://www.cnblogs.com/skywang12345/p/3479024.html)

The thread altogether consists of the following 5 states.
1. new state : When the thread object is created, it enters the new state. At this point it is just like other Java objects, where only the Java virtual machine allocates memory and initializes its member variable values.

2. ready State (Runnable): Also known as "executable State". The thread object is called the start () method of the object, and the thread is in the ready state. Java Virtual Opportunity creates method call stacks and program counters for it. A thread that is in a ready state may be executed by the CPU at any time, depending on the schedule of the JVM's Threads scheduler.

3. running State (Running) : Thread gets CPU permission to execute. It is important to note that a thread can only go from a ready state to a running state.

4. blocking State (Blocked) : The blocking state is a temporary stop for a thread that has abandoned the CPU usage for some reason. Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three types of blocking:
wait for blocking--by calling the thread's Wait () method, to let the thread wait for a job to complete.
(02) Synchronization blocking--the thread acquires a synchronized synchronization lock failure (because the lock is occupied by another thread), it goes into a synchronous blocking state.
(03) Other blocking-- the thread enters the blocking state by calling the thread's sleep () or join () or making an I/O request. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state.

5. Death Status (Dead) : The thread finishes executing, exits the run () method due to an exception, or calls the thread's Stop () method (which is prone to deadlock, which is now deprecated), which ends the life cycle.

Four, Wait (), notify (), Nofityall () methods

In Object.java, methods such as Wait (), notify (), and notifyall () are defined.

The role of Wait () is to let the current thread go into a wait state, andwait () also causes the current thread to release the locks it holds .

The role of Notify () and Notifyall () is to wake up the waiting thread on the current object, notify () is to wake up a single thread, and Notifyall () is to wake up all the threads.

The following API details about wait/wake in the object class are as follows:
Notify ( ) --wakes up a single thread waiting on this object monitor and puts it into "ready state".      
Notifyall ()--wakes all the threads waiting on this object monitor and puts them into "ready state".
Wait ()--keeps the current thread in a "waiting (blocking) state" until the other thread calls the Notify () method of this object or the Notifyall () method, and the current thread is awakened (in "Ready state").
Wait (long timeout)--leave the current thread in a "waiting (blocking) state" until the other thread calls the Notify () method of this object or the Notifyall () method, or exceeds the specified amount of time ", the current thread is called (enter "Ready state").
Wait (long timeout, int nanos)--Leave the current thread in a "waiting (blocking) state" until another thread calls the Notify () method of this object or the Notifyall () method, or some other thread interrupts the current line The current thread is awakened (into ready state), or the actual amount of time has been exceeded.

The role of Wait () is to allow the current thread to wait (release the lock), while the "current thread" is the thread that is running on the CPU!

Here, the http://www.cnblogs.com/skywang12345/p/3479224.html example is very detailed.

v. Yield (), sleep (), join (), and interrupt () methods

1. Yield ()

Yield () is a static method of the thread class . It allows the current thread to pause, but does not block the thread, but rather the "running state" enters the "ready state", allowing other waiting threads with the same priority to get execution, but there is no guarantee that other threads with the same priority will be able to gain execution after the current thread calls yield (). It is also possible that the current thread has entered the "running state" and continues to run!

It is important to note that theyield () method does not release the lock .

2. Sleep ()

Sleep () is a static method of the thread class. The method declaration throws a interrupedexception exception. So when used, either catch or declare the throw.

There are 2 types of overloaded methods:

--static void Sleep (long Millis): Allows the currently executing thread to pause for millis milliseconds and into a blocking state, which is affected by the precision and accuracy of the system timer and thread scheduler.

--static void Sleep (long millis, int nanos): lets the currently executing thread pause Millis milliseconds plus Nanos microseconds , and Into the blocking state, the method is affected by the precision and accuracy of the system timer and thread scheduler.

The function of sleep () is to let the current thread hibernate, that is, the current thread goes from "Running state" to "hibernate (blocked) state". Sleep () Specifies the sleep time at which the thread sleeps longer than/equal to the sleep time, and when it is woken up, it is changed from "blocked state" to "ready state", thus waiting for the CPU to schedule execution. Frequently used to pause the operation of a program.

Also note that thesleep () method does not release the lock .

3. Join ()

Join () is an instance method of thread. Indicates that when a program executes a join method that calls other threads in the stream, the calling thread is blocked until the thread of the join has finished executing.

There are 3 kinds of overloaded forms:

--join (): Waiting for the join thread to finish executing

--join (Long Millis): The thread that waits for the join is the longest of millis milliseconds, and does not wait if the thread of the join has not finished executing within Millis milliseconds.

--join (long millis, int nanos): The thread that waits for the join is the longest of Millis milliseconds plus Nanos microseconds, and does not wait if the thread that is being join has not finished executing during this time.

That is, within the current thread, after calling join () with a thread object, the current thread waits until the thread of the thread object finishes running and the original thread continues to run.

4, Interrupt ()  

We often control threads by judging the thread's interrupt token.

Interrupt () is an instance method of the thread class that interrupts this thread. When this method is called, the thread's interrupt flag is set to "true" immediately. So when an interrupt is in a "blocked" thread, the interrupt token is set to "false" and a interruptedexception is thrown because it is in a blocking state. So we catch this exception in the loop outside of the thread, and we can exit the threads.

Interrupt () does not interrupt the "running" thread, it sets the thread's "break token" to true, so we can constantly detect the interrupt token through isinterrupted () , thus calling the interrupt () After terminating the thread, this is also the usual use of our interrupt ().

interrupted () is a static method of the thread class that returns a Boolean type that indicates whether the current thread has been interrupted, isinterrupted () is an instance method of the thread class, and returns a Boolean type to determine whether the thread has been interrupted. They can be used to detect the "interrupt token" of an object. The difference is that interrupted (), in addition to returning the interrupt token, clears the interrupt token (setting the interrupt token to false), and isinterrupted () simply returns the interrupt token.

Six, synchronized keyword

1. Principle

In Java, each object has and has only one synchronization lock. This also means that the synchronization lock is dependent on the object and exists.

When the synchronized method of an object is called by the front thread, the synchronization lock of the object is acquired.    For example, synchronized (obj), the current thread acquires the synchronization lock for the object "obj".

The access of different threads to the synchronization lock is mutually exclusive.   that is, at some point in time, the object's synchronization lock can only be obtained by one thread! With a synchronous lock, we are able to implement mutually exclusive access to the object/method in multiple threads. For example, there is now a thread A and thread B, and they all access the synchronization lock for object obj. Suppose, at some point, thread a acquires the "synchronous lock of obj" and performs some action, and at this point, thread B also attempts to acquire "the synchronous lock of obj"--thread B Gets the failure, it must wait until thread a releases "the object's synchronization lock" and thread B gets to "Obj's synchronous lock" So that they can run.

2. Basic rules

 First: When a thread accesses the "synchronized method" or "Synchronized code block" of "an object", the other thread accesses the " synchronized Method" or "Synchronized code block" of the object. will be blocked.
Second: When a thread accesses the "synchronized method" or "Synchronized code block" of an object, other threads can still access the non-synchronized code block of the object .
Third: When a thread accesses the "synchronized method" or "Synchronized code block" of "an object", other threads access to other "synchronized methods" or "synchronized code blocks" of the object will be blocked.

3. Instance lock and Global lock

Instance Lock --locks on an instance object. If the class is a singleton, then the lock also has the concept of a global lock.
The instance lock corresponds to the synchronized keyword.
Global Lock --The lock is for a class, and the thread shares the lock regardless of the number of objects in the instance.
A global lock corresponds to a static synchronized (or a lock on a class or ClassLoader object).

That is, a synchronized keyword on a non-static method that represents the method relies on its owning object. A static method on the Synchronized keyword that represents the method that relies on the class itself.

Vii. Thread Priority and Daemon threads

1. Thread Priority

The range of thread priorities in Java is 1~10, and the default priority is 5. The default priority for each thread has the same priority as the parent thread that created it. By default, the Mian thread has a normal priority. High-priority threads take precedence over low-priority threads. Thread provides the setpriority (int newpriority) and getpriority () methods to set and return thread precedence.

The thread class has 3 static constants:

--max_priority = 10

--min_priority = 1

--norm_priority = 5

2. Daemon Thread

There are two types of threads in Java: The user thread and the daemon thread . They can be distinguished by the Isdaemon () method: If False is returned, the thread is a "user thread" or "Daemon thread".
User threads typically perform user-level tasks, while daemons, which are "background threads", are typically used to perform background tasks. It is important to note that the Java virtual machine exits after the user thread has finished.

The daemon thread, also known as "Background thread", "Sprite Thread", has a feature-- if all foreground threads are dead, the background thread automatically dies .

  sets a thread by Setdaemon (true) .

A summary of the various knowledge of Java, recommend everyone a blogger skywang12345, his various Java knowledge summary is detailed and easy to understand and classic, gave me a lot of help.

Reference:http://www.cnblogs.com/skywang12345/p/java_threads_category.html

"Crazy Java Handout"

Java Multithreading Summary (i) Multithreading basics

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.