In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to quickly understand Java multithreading". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to quickly understand Java multithreading".
Thread
The concept of threads:
Thread (English: Thread) is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operating unit of the process. A thread refers to a single order of control flow in a process, where multiple threads can be concurrent in a process, and each thread performs different tasks in parallel. It is also called lightweight process (Lightweight Processes) in Unix System V and SunOS, but lightweight process refers more to kernel thread (Kernel Thread) and user thread (User Thread) is called thread.
1.1 differences between threads and processes
Process: an application that is running in the system; once a program is run, it is a process; a process-the smallest unit of resource allocation.
Thread: the basic unit in which the system allocates processor time resources, or a unit execution flow that executes independently within a process. Thread-the smallest unit of program execution.
That is, a process can contain multiple threads, and threads are the smallest unit of program execution.
1.2 status of the thread
NEW: thread has just been created
RUNNABLE: a running thread in JVM, in which the running state can have two running states, RUNNING and READY, which are scheduled by the system to change the state.
BLOCKED: the thread is blocked, waiting for the monitor lock, and can be re-executed in the synchronous code block.
WAITING: wait statu
TIMED_WAITING: calling the sleep () join () wait () method may cause the thread to be in a waiting state
TERMINATED: thread has finished executing and has exited
1.3 Notify and Wait:
The role of Notify and Wait
First of all, let's take a look at the explanation given by the source code, which is translated here:
Notify: wakes up a thread monitoring that is waiting for this object. If any thread is waiting for this object, one of them is selected to be awakened. The choice is arbitrary and occurs at the discretion of execution. A thread waits for an object to monitor by calling a {@ code wait} method.
Notify () needs to be called in a synchronization method or synchronization block, that is, the thread must also acquire an object-level lock on the object before calling it.
Wait: causes the current thread to wait until another thread calls the {@ link java.lang.Object#notify ()} method or the {@ link java.lang.Object#notifyAll ()} method.
In other words, this method behaves as if it were simple to execute the call {@ code wait (0)}. The current thread must have a monitor for the object.
The thread releases ownership of this monitor and waits for another thread to notify the thread waiting for the monitor of the object to wake up by calling the {@ code notify} method or the {@ code notifyAll} method. The thread then waits until it can regain ownership of the monitor and then continues to execute.
The purpose of Wait () is to make the currently executing thread wait, which is a method of the Object class that places the current thread in a pre-execution queue and stops execution at the line of code where Wait is located until it is notified or interrupted.
Before calling the Wait method, the thread must acquire an object-level lock on the object, that is, the Wait method can only be called in a synchronous method or synchronous block.
The difference between Wait and Sleep:
The biggest essential difference between them is that Sleep () does not release the synchronization lock and Wait () releases the synchronization lock.
There is also a difference in usage: Sleep (milliseconds) can use the time specified to make him wake up automatically, if the time is not up, you can only call Interreput () to force a break; Wait () can be called directly with Notify ().
These two methods come from different classes: Thread and Object.
The main reason is that the Sleep method does not release the lock, while the Wait method releases the lock, allowing other threads to use synchronization control blocks or methods.
1.4 similarities and differences between Thread.sleep () and Thread.yield ()
Same: both Sleep () and yield () release CPU.
Different: Sleep () brings the current thread into a stagnant state, so the thread executing Sleep () will definitely not execute within a specified period of time; yield () just brings the current thread back to the executable state, so the thread executing yield () may be executed again as soon as it enters the executable state. Sleep () can give low-priority threads a chance to execute, and of course, it can also give execution opportunities to threads with the same priority and high priority; yield () can only give threads with the same priority a chance to execute.
1.5 add: the concept of deadlock
Deadlock: a phenomenon in which two or more processes (or threads) wait for each other due to competition for resources during execution. Without external force, they will not be able to push forward. At this point, it is said that the system is in a deadlock state or the system has a deadlock, and these processes that are always waiting for each other are called deadlock processes.
Four necessary conditions for deadlocks (none of which are indispensable):
Mutually exclusive condition: as the name implies, thread access to resources is exclusive and can only be occupied by the next thread when the thread releases resources.
Request and keep: to put it simply, you don't let go and wait for new resources. Thread T1 has kept at least one resource R1 occupied, but made a request for another resource R2, and at this time, resource R2 is occupied by other threads T2, so that thread T1 must also wait, but does not release the resource R1 it maintains.
Undeprivation: other linearity cannot be deprived when resources are not used up.
Loop waiting: always waiting for the other thread to release resources.
We can destroy the formation of deadlock according to the four necessary conditions of deadlock.
1.6 add: the difference between concurrency and parallelism
Concurrency: refers to the alternating execution of tasks by multiple tasks within a certain period of time. When there are multiple threads in operation, the CPU run time is divided into several time periods, and then the time periods are allocated to each thread for execution. While the thread code for a period of time is running, other threads are suspended.
Parallelism: the ability to handle multiple tasks at the same time. The ability of CPU to process requests from multiple threads when they are operating at the same time.
The difference is whether CPU can handle all tasks at the same time, concurrency can not, parallel can.
1.7 add: three elements of thread safety
Atomicity: Atomic package, CAS algorithm, Synchronized, Lock.
Visibility: Synchronized, Volatile (atomicity is not guaranteed).
Orderliness: Happens-before rules.
1.8 add: how to achieve thread safety
Mutually exclusive synchronization: Synchronized, Lock.
Non-blocking synchronization: CAS.
A solution that does not require synchronization: if a method does not involve sharing data in the first place, it naturally does not need any synchronization to ensure correctness.
1.9 add: mechanisms to ensure thread safety:
Synchronized keyword
Lock
CAS, atomic variable
ThreadLocl: to put it simply, each thread has its own unique copy of the same variable, and each thread actually accesses its own object, so there is no thread safety problem.
Volatile
Copy on CopyOnWrite Writin
With the increase of CPU core and the rapid development of Internet, the processing speed of single-thread program can not keep up with the development speed and the growth rate of large amount of data. Multithreading arises at the historic moment, making full use of CPU resources, while greatly improving the processing speed of the program.
How to create a thread
Inherit the Thread class:
Public class ThreadCreateTest {public static void main (String [] args) {new MyThread (). Start ();}} class MyThread extends Thread {@ Override public void run () {System.out.println (Thread.currentThread (). GetName () + "\ t" + Thread.currentThread (). GetId ());}}
Implement the Runable interface:
Public class RunableCreateTest {public static void main (String [] args) {MyRunnable runnable = new MyRunnable (); new Thread (runnable). Start ();}} class MyRunnable implements Runnable {@ Override public void run () {System.out.println (Thread.currentThread (). GetName () + "\ t" + Thread.currentThread (). GetId ());}}
Create threads through Callable and Future:
Public class CallableCreateTest {public static void main (String [] args) throws Exception {/ / wrapping Callable as FutureTask,FutureTask is also a Runnable MyCallable callable = new MyCallable (); FutureTask futureTask = new FutureTask (callable); new Thread (futureTask). Start (); / / the get method blocks the calling thread Integer sum = futureTask.get () System.out.println (Thread.currentThread (). GetName () + Thread.currentThread (). GetId () + "=" + sum);}} class MyCallable implements Callable {@ Override public Integer call () throws Exception {System.out.println (Thread.currentThread (). GetName () + "\ t" + Thread.currentThread (). GetId () + "\ t" + new Date () + "\ tstarting..."); int sum = 0 For (int I = 0; I
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.