In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what are the concurrent knowledge points of Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what are the Java concurrent knowledge points"!
1. What's the difference between parallelism and concurrency?
From the operating system's point of view, threads are the smallest unit allocated by CPU.
Parallelism is when both threads are executing at the same time. This requires two CPU to execute two threads respectively.
Concurrency is that there is only one execution at the same time, but within a period of time, both threads are executed. The implementation of concurrency depends on CPU switching threads, because the switching time is very short, so it is basically unaware of the user.
It's like when we go to the canteen to eat, parallel means that we line up in multiple windows, and several aunts play food at the same time; at the same time, we squeeze together in one window, and the aunt gives one spoonful to this and the other in a hurry.
two。 Tell me what are processes and threads?
To talk about threads, you have to talk about processes first.
Process: a process is a running activity of code on a data set, and it is the basic unit of resource allocation and scheduling for the system.
Thread: a thread is an execution path of a process, there is at least one thread in a process, and multiple threads in the process share the resources of the process.
The operating system allocates resources to processes when it allocates resources, but CPU resources are special. It is allocated to threads. Because threads really occupy CPU to run, it is also said that threads are the basic unit of CPU allocation.
For example, in Java, when we start the main function, we actually start a JVM process, and the thread of the main function is a thread in this process, also known as the main thread.
There are multiple threads in a process, and multiple threads share the heap and method zone resources of the process, but each thread has its own program counter and stack.
3. How many ways can threads be created?
There are three main ways to create threads in Java, which are inheriting Thread class, implementing Runnable interface and implementing Callable interface.
Inherit the Thread class, override the run () method, and call the start () method to start the thread
Public class ThreadTest inherits the Thread class * / public static class MyThread extends Thread {@ Override public void run () {System.out.println ("This is child thread");}} public static void main (String [] args) {MyThread thread = new MyThread (); thread.start ();}}
Implement the Runnable interface and override the run () method
Public class RunnableTask implements Runnable {public void run () {System.out.println ("Runnable!");} public static void main (String [] args) {RunnableTask task = new RunnableTask (); new Thread (task). Start ();}}
Neither of the above returns a value, but what if we need to get the execution result of the thread?
Implement the Callable interface and override the call () method, which allows you to get the return value of the task execution through FutureTask
Public class CallerTask implements Callable {public String call () throws Exception {return "Hello,i am running!";} public static void main (String [] args) {/ / create asynchronous task FutureTask task=new FutureTask (new CallerTask ()); / / start thread new Thread (task) .start () Try {/ / waits for execution to complete and gets the returned result String result=task.get (); System.out.println (result);} catch (InterruptedException e) {e.printStackTrace ();} catch (ExecutionException e) {e.printStackTrace ();} 4. Why does the run () method execute when the start () method is called, and why not call the run () method directly?
When JVM executes the start method, it first creates a thread, and the new thread created executes the run method of thread, which has the effect of multithreading.
* * Why can't we just call the run () method? * * it is also clear that if the run () method of Thread is called directly, the run method is still running in the main thread, which is equivalent to sequential execution, which does not have the effect of multithreading.
5. What are the common scheduling methods for threads?
Thread waiting and notification
There are some functions in the Object class that can be used to wait and notify threads.
Wait (): when a thread A calls the wait () method of a shared variable, thread An is blocked and suspended, and the following situations occur before it returns:
(1) Thread A calls the shared object notify () or notifyAll () method
(2) other threads call the interrupt () method of thread A, and thread A returns with an InterruptedException exception.
Wait (long timeout): this method has an extra timeout parameter than the wait () method. The difference is that if thread A calls the wait (long timeout) method of the shared object and is not awakened by another thread within the specified timeout ms time, then this method will still return because of the timeout.
Wait (long timeout, int nanos), which internally calls the wait (long timout) function.
The above is the method of thread waiting, and there are two main ways to wake up thread:
Notify (): after a thread A calls the notify () method of a shared object, it wakes up a thread that is suspended after calling the wait series methods on this shared variable. There may be multiple threads waiting on a shared variable, and it is random to wake up which waiting thread.
NotifyAll (): unlike calling the notify () function on a shared variable to wake up a thread that is blocked on the shared variable, the notifyAll () method wakes up all threads that are suspended by calling the wait series methods on the shared variable.
The Thread class also provides a method for waiting:
Join (): if a thread An executes the thread.join () statement, it means that the current thread A waits for the thread to terminate.
Return from thread.join ().
Thread hibernation
Sleep (long millis): a static method in the Thread class. When an executing thread A calls the sleep method of Thread, thread A temporarily relinquishes the right to execute at a specified time, but thread A has monitor resources, such as locks, that hold and do not give up. The function will return normally after the specified sleep time, and then participate in the scheduling of CPU. After obtaining the CPU resources, the function can continue to run.
Give priority
Yield (): a static method in the Thread class, when a thread calls the yield method, it is actually implying that the thread scheduler is currently requesting to give up its CPU, but the thread scheduler can ignore this hint unconditionally.
Thread interrupt
Thread interruption in Java is a mode of cooperation between threads. By setting the interrupt flag of a thread, the execution of the thread can not be terminated directly, but the interrupted thread handles itself according to the interrupt state.
Void interrupt (): interrupts a thread, for example, when thread An is running, thread B can call the interrupt () method to set the thread's interrupt flag to true and return immediately. Setting the flag is just setting the flag. Thread An is actually not interrupted and will continue to execute.
The boolean isInterrupted () method detects whether the current thread is interrupted.
The boolean interrupted () method: detects whether the current thread is interrupted, and unlike isInterrupted, this method clears the interrupt flag if it finds that the current thread is interrupted.
6. How many states does a thread have?
In Java, threads have six states:
State description NEW initial state: the thread has been created, but the start () method RUNNABLE has not been called the running state: the Java thread generally calls the ready and running states in the operating system "running" BLOCKED blocking state: indicates that the thread is blocking the lock WAITING waiting state: indicates that the thread enters the waiting state Entering this state indicates that the current thread needs to wait for other threads to take some specific actions (notification or interrupt) TIME_WAITING timeout wait state: this state is different from WAITIND, it is the TERMINATED termination state that can be returned at a specified time: indicates that the current thread has finished executing
Threads are not fixed in a certain state during their own life cycle, but switch between different states as the code executes. The state of the Java thread changes as shown in the figure:
7. What is thread context switching?
The purpose of using multithreading is to take full advantage of CPU, but we know that concurrency is actually a CPU to deal with multiple threads.
In order to make users feel that multiple threads are executing at the same time, the allocation of CPU resources uses time slice rotation, that is, each thread is assigned a time slice, and the thread takes up CPU to execute tasks in the time slice. When the thread has finished using the time slice, it will be in a ready state and let the CPU be occupied by other threads, which is called context switching.
8. Does the daemon thread understand?
Threads in Java are divided into two categories: daemon threads (daemon threads) and user threads (user threads).
The main function is called when JVM starts, and the main function is located in a user thread. In fact, many daemon threads are also started within JVM, such as garbage collection threads.
So what's the difference between a daemon thread and a user thread? One of the differences is that when the last non-daemon thread bundle occurs, the JVM exits normally, regardless of whether the daemon thread currently exists, that is, whether the daemon thread ends or not does not affect the JVM exit. In other words, JVM does not normally exit as long as one user thread is not finished.
9. What are the ways of communication between threads?
Volatile and synchronized keywords
The keyword volatile can be used to modify fields (member variables), that is, to tell the program that any access to the variable needs to be obtained from shared memory, and that changes to it must be synchronously flushed back to shared memory, which ensures the visibility of variable access by all threads.
The keyword synchronized can be used in the form of a method or a synchronous block. It mainly ensures that multiple threads can only have one thread in the method or synchronous block at the same time. It ensures the visibility and exclusiveness of thread access to variables.
Waiting / notification mechanism
You can use Java's built-in wait / notification mechanism (wait () / notify ()) to enable one thread to modify the value of an object while another thread senses the change and then acts accordingly.
Pipeline input / output stream
The difference between pipe input / output stream and ordinary file input / output stream or network input / output stream is that it is mainly used for data transfer between threads, while the medium of transmission is memory.
The pipeline input / output stream mainly includes the following four specific implementations: PipedOutputStream, PipedInputStream, PipedReader and PipedWriter, the first two are byte-oriented and the last two character-oriented.
Use Thread.join ()
If a thread An executes the thread.join () statement, it means that the current thread A waits for the thread to terminate before returning from thread.join (). In addition to providing the join () method, thread Thread also provides two timeout methods, join (long millis) and join (long millis,int nanos).
Use ThreadLocal
ThreadLocal, that is, thread variables, is a storage structure with ThreadLocal objects as keys and arbitrary objects as values. This structure is attached to the thread, which means that a thread can query a value bound to the thread based on a ThreadLocal object.
You can set a value through the set (T) method, and then get the previously set value under the current thread through the get () method.
With regard to multithreading, there is a high probability that there will be some written examination questions, such as alternating printing, bank transfer, production and consumption model, etc., and the third will issue a separate issue to check the common multithreaded written questions.
ThreadLocal
In fact, there are not many ThreadLocal application scenarios, but it is an old Youtiao that has been bombed thousands of times, involving multithreading, data structures and JVM. There are many questions that can be asked, so be sure to win.
What is 10.ThreadLocal?
ThreadLocal, that is, the thread local variable. If you create a ThreadLocal variable, then each thread accessing the variable will have a local copy of the variable. When multiple threads operate on this variable, they are actually operating on variables in their own local memory, thus playing the role of thread isolation and avoiding thread safety problems.
Create
A ThreadLoca variable localVariable is created, and any thread can access the localVariable concurrently.
/ / create a ThreadLocal variable public static ThreadLocal localVariable = new ThreadLocal ()
Write
Threads can use localVariable anywhere to write variables.
LocalVariable.set ("I am three")
Read
Everywhere a thread reads, it is the variable it writes.
LocalVariable.get (); 11. Have you ever used ThreadLocal in your work?
What is useful, it is used to store the context of user information.
Our system application is a typical MVC architecture. Every time the logged-in user accesses the interface, he will carry a token in the request header. According to this token, the basic information of the user can be parsed in the control layer. So the question is, what if user information is used in both the service layer and the persistence layer, such as rpc calls, updating user feeds, and so on?
One way is to explicitly define user-related parameters, such as account number, user name. In this way, we may need to modify the code in a large area, a little bit of melon peel, so what should we do?
At this point, we can use ThreadLocal to intercept requests to store user information in ThreadLocal at the control layer, so that we can retrieve user data stored in ThreadLocal anywhere.
Data isolation of cookie, session, and so on in many other scenarios can also be achieved through ThreadLocal.
ThreadLocal is also used in our commonly used database connection pool:
The connection of the database connection pool is managed by ThreadLoca to ensure that the operation of the current thread is the same Connnection.
How does 12.ThreadLocal work?
Let's take a look at the set (T) method of ThreadLocal and find that we first get the current thread, then get the ThreadLocalMap, and then store the element in this map.
Public void set (T value) {/ / get the current thread Thread t = Thread.currentThread (); / / get ThreadLocalMap ThreadLocalMap map = getMap (t); / / store the current element in map if (map! = null) map.set (this, value); else createMap (t, value);}
The secret of the ThreadLocal implementation lies in this ThreadLocalMap, but a member variable threadLocals of type ThreadLocal.ThreadLocalMap is defined in the Thread class.
Public class Thread implements Runnable {/ / ThreadLocal.ThreadLocalMap is an attribute of Thread ThreadLocal.ThreadLocalMap threadLocals = null;}
Since ThreadLocalMap is called Map, there is no doubt that it is a type data structure. We all know that the essence of map is an array of formal nodes, so what are the nodes of ThreadLocalMap?
Static class Entry extends WeakReference
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.