Java multithreading Summary (1) multithreading Basics

Source: Internet
Author: User

Multithreading is an important aspect of Java learning and a basic skill that every Java programmer must possess. This article is just a Summary of the details and nature of multithreading, and does not have an example of getting started with code. It is not suitable for beginners to understand. It is recommended that beginners read books and read blog posts to try to write code.

For more information, see http://www.cnblogs.com/zrtqsk/p/3776328.html. thank you!

I. Process

A process is the basis of the operating system structure, a program execution, and an 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 one Process ). A program enters the memory and runs into a process. A process is a running program and has certain independent functions. There is a classic saying that a process is an independent unit for the system to allocate and schedule resources.

Processes have the following features:

1,Independence. A process is an entity that exists independently in the system. It has its own independent resources and its own private address space.

2,Dynamic. The essence of a process is an execution process of a program in multiple program systems. The process is generated dynamically and disappears dynamically. A process has its own lifecycle and different states.

3,Concurrency. Any process can be concurrently executed with other processes.

(Note: concurrency and parallel are different. Parallelism means that multiple commands run simultaneously on multiple processors at the same time. Concurrency means that only one command can be executed at a time, but multiple process commands are quickly rotated and executed, as if multiple commands are executed at the same time .)

4,Asynchronization: Due to mutual control between processes, the process has an intermittent execution, that is, the process is pushed forward at an independent and unpredictable speed.

5,Structural Features: ProcessProgram,DataAndProcess Control BlockIt consists of three parts.

 

 

Ii. Thread

A thread, sometimes called a Lightweight Process (LWP), is the smallest unit of the program execution flow. A standard thread consists of the thread ID, current Instruction Pointer (PC), register set, and stack. In addition, a thread is an entity in a process and the basic unit for independent scheduling and distribution by the system,A thread does not own system resources and only has a little necessary resources during running. However, a thread can share all resources owned by a process with other threads of the same process.. One thread can create and withdraw another thread, and multiple threads in the same process can execute concurrently. Due to mutual constraints between threads, the threads are intermittently running. Each program has at least one thread. If the program has only one thread, it is the program itself.

A thread is a single sequential control flow in a program. It is called multithreading.

 

 

Iii. thread status

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

Threads are in the following five states.
1.New): After a thread object is created, it enters the new state. In this case, like other Java objects, the memory is allocated only by the Java Virtual Machine and Its member variable value is initialized.

2.Ready state (Runnable): It is also called "executable status ". The thread object is called the start () method of the object, and the thread is ready. The Java virtual machine creates a method call stack and a program counter for it. A thread in the ready state may be scheduled and executed by the CPU at any time, depending on the scheduling of the thread scheduler in the JVM.

3.Running status (Running): The thread obtains the CPU permission for execution. Note that the thread can only enter the running state from the ready state.

4.Blocked): The thread stops running temporarily because the CPU usage is abandoned for some reason. It is not until the thread enters the ready state that it has the opportunity to go to the running state. Blocking is divided into three types:
(01) waiting for blocking-call the wait () method of the thread to let the thread wait for the completion of a job.
(02) Synchronization blocking: the thread fails to get the synchronized synchronization lock because it is occupied by other threads.
(03) Other blocking: When the thread sleep () or join () or sends an I/O Request, the thread enters the blocking state. When the sleep () status times out, the join () waits for the thread to terminate or times out, or the I/O processing is completed, the thread enters the ready state again.

5.Dead): The run () method has been executed, exited due to an exception, or the stop () method of the thread has been directly called (it is easy to cause a deadlock and is not recommended for use now ), this thread ends the lifecycle.

 

 

4. wait (), notify (), and nofityAll () Methods

In Object. java, methods such as wait (), Policy (), and policyall () are defined.

Wait () is used to bring the current thread into the waiting state. At the same time,Wait () will also let the current thread release the lock it holds.

The functions of Y () and notifyAll () are to wake up the waiting thread on the current object. Y () is to wake up a single thread, while policyall () is to wake up all threads.

The following is the detailed information about the waiting/Wakeup API in the Object class:
  Running y () -- wake up a single thread waiting on this object monitor and make it "ready ".
Yyall () -- wake up all threads waiting on this object monitor and bring them to the ready state ".
Wait () -- puts the current thread in the "waiting (blocking) State", "until other threads call the notify () method or notifyAll () method of this object ", the current thread is awakened (enters the ready state ").
Wait (long timeout) -- puts the current thread in the "waiting (blocking) State", "until other threads call the notify () method or yyall () method of this object, or exceeds the specified time, the current thread is awakened (enters the ready state ").
Wait (long timeout, int nanos) -- puts the current thread in the "waiting (blocking)" state, "until other threads call the notify () method or notifyAll () method of this object, or if another thread breaks the current thread or exceeds the actual time, the current thread is awakened (entering the ready state ").

 Wait () is used to wait for the "current thread" (the lock will be released), while "current thread" refers to the thread running on the cpu!

Http://www.cnblogs.com/skywang12345/p/4109224.html.

 

 

V. yield (), sleep (), join (), andInterrupt ()Method

1. yield ()

Yield () is a static method of the Thread class. It can suspend the current thread, but does not block the thread. Instead, it enters the ready state from the "Running State", so that other waiting threads with the same priority can obtain the execution right. However, it is not guaranteed that after the current thread calls yield (), other threads with the same priority will be able to obtain the execution right. It may also be that the current thread enters the "running" status to continue running!

It is worth noting that,The yield () method does not release the lock..

 

2. sleep ()

Sleep () is a static method of the Thread class. The method declaration throws an InterrupedException exception. Therefore, when used, either capture or declare to throw.

There are two reload methods:

-- Static void sleep (long millis): Pause the currently executed thread in milliseconds and enter the blocking status, this method is affected by the precision and accuracy of the system timer and thread scheduler.

-- Static void sleep (long millis, int nanos): Pause the currently running thread in millis milliseconds, add nanos microseconds, and enter the blocking status, this method is affected by the precision and accuracy of the system timer and thread scheduler.

Sleep () is used to sleep the current thread, that is, the current thread enters the sleep (blocking) state from the "running state ". Sleep () specifies the sleep time. The sleep time of a thread is later than or equal to the sleep time. When the thread is awakened again, the sleep time changes from blocking to ready ", so as to wait for cpu scheduling. It is often used to pause the running of a program.

Note that,The sleep () method does not release the lock..

 

3. join ()

Join () is an instance method of Thread. Indicates that when the join method of another thread is called in the execution flow of a program, the calling thread is blocked until the execution of the joined thread is completed.

There are three reloads:

-- Join (): Wait until the execution of the joined thread is completed.

-- Join (long millis): The maximum waiting time for the joined thread is millis millisecond. If the joined thread has not finished execution within millis milliseconds, do not wait.

-- Join (long millis, int nanos): The maximum waiting time for the joined thread is millis millisecond plus nanos microsecond. If the joined thread has not been executed yet, then do not wait.

That is, after a thread object is called join () in the current thread, the current thread will wait until the thread of the thread object has finished running.

 

4. interrupt () 

Interrupt is located in the Thread class and used to interrupt the Thread. When a thread in the "blocking" status is interrupted, the interrupt mark is cleared because it is in the blocking status, so an InterruptedException is thrown. Interrupt () does not interrupt a thread in the "running" state, and sets the thread's "interrupt mark" to true.

It is worth noting that both interrupted () and isInterrupted () can be used to detect the "interrupt mark" of an object ". The difference is that interrupted () removes the interrupt mark (that is, set the interrupt mark to false) in addition to the return interrupt mark, while isInterrupted () Only returns the interrupt mark.

 

 

6. Synchronized keywords

1. Principle

In java, each object has only one synchronization lock. This also means that the synchronization lock is dependent on objects.

When we call the synchronized Method of an object, we obtain the synchronization lock of this object. For example, synchronized (obj) obtains the synchronization lock of the object obj.

Access to synchronization locks by different threads is mutually exclusive.That is to say, at a certain point in time, the synchronization lock of an object can only be obtained by one thread! With the synchronization lock, we can implement mutex access to "Object/Method" in multiple threads. For example, there is A thread A and thread B, and they all access the "synchronization lock of object obj ". Assume that at A certain time point, thread A obtains the "obj synchronization lock" and performs some operations. At this time, thread B also tries to get the "obj synchronization lock" -- thread B fails to get the lock, and it must wait, it is not until thread A releases the "synchronization lock of this object" that thread B can obtain the "obj synchronization lock" to run.

 

2. Basic Rules

Article 1: When a thread accesses the "synchronized Method" or "synchronized code block" of "an object", other threadsAccess to the "synchronized Method" or "synchronized code block" of "this object"Will be blocked.
Article 2: When a thread accesses the "synchronized Method" or "synchronized code block" of "an object", other threads stillAttackers can access non-synchronous code blocks of the object..
Article 3: When a thread accesses the "synchronized Method" or "synchronized code block" of "an object", other threadsAccess to other "synchronized methods" or "synchronized code block" of "this object"Will be blocked.

 

3. instance locks and global locks

Instance lock-- Lock on an instance object. If this type is a singleton instance, 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. The thread shares the lock regardless of the number of objects in the instance.
The global lock corresponds to static synchronized (or the lock is on the class or classloader object of this class ).

That is, the synchronized keyword on a non-static method indicates that the method depends on its object. The synchronized keyword on a static method indicates that the method depends on the class itself.

 

 

VII. thread priority and daemon thread

1. thread priority

The thread priority in java ranges from 1 ~ 10. The default priority is 5. The default priority of each thread is the same as that of the parent thread that created it. By default, the mian thread has a normal priority. The "high-priority thread" takes precedence over the "low-priority thread" for execution. Thread provides the setPriority (int newPriority) and getPriority () Methods to set and return the Thread priority.

The Thread class has three static constants:

-- MAX_PRIORITY = 10

-- MIN_PRIORITY = 1

-- NORM_PRIORITY = 5

 

2. daemon thread

Java has two threads:User threadAndDaemon thread. You can use the isDaemon () method to differentiate them: If false is returned, the thread is a "User thread"; otherwise, the thread is a "daemon thread ".
User threads are generally used to execute user-level tasks, while the daemon thread is also the "background thread", which is generally used to execute background tasks. It should be noted that the Java Virtual Machine will exit after the "user thread" ends.

The daemon thread, also known as "background thread" and "Genie thread", has a feature --If all foreground threads die, background threads automatically die..

SetDaemon (true) is used to set a thread.

 

 

 

We recommend that you use skywang12345, a blogger, to summarize the various Java knowledge, which is easy to understand and classic. It has helped me a lot.

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

Crazy Java handout

 

If you think this article is not bad, please click to recommend it! Thank you!

 

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.