In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what is the cooperation between threads?" in the operation of actual cases, many people will encounter such a dilemma, and then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
I. the state of the thread
There are five kinds of states in threads in Java: New (new state), Runnable (ready state), Running (running state), Blocked (blocking state), and Dead (dead state).
New: new state, which is created when the thread is created, that is, new Thread (…) Before the start method is called, the thread is in a new state
Runnable: ready state, when the thread's start method is called, the thread enters the ready state, waiting for the CPU resource. Threads in the ready state are scheduled by the thread scheduler (thread scheduler) of the Java runtime system.
Running: in the running state, the thread in the ready state enters the running state after obtaining the right to execute the CPU and starts executing the run method.
Blocked: blocking state, the thread did not finish execution, due to some reason (for example, the Icano operation, etc.) to give up the right to execute CPU, itself into the blocking state.
Dead: dead state. If a thread finishes or an exception occurs during execution, the thread will enter the dead state.
The transition relationship between these five states is shown in the following figure:
With a basic understanding of these five states, let's take a look at how these transitions are implemented in Java.
Hello, everyone, I am AIO Life, follow me, follow up more technical difficulties, the article has shortcomings, welcome to comment, thank you!
By the way, to help you organize some JAVA e-books, scan the code to reply "1024" to get a collection of e-books, you can also sign to get cash red envelopes.
Warm winter return blood ~
A total of three versions of the methods are available in JDK
The wait () method suspends the currently running thread until the notify or notifyAll method wakes up the thread.
Wait (long timeout), which is similar to the wait () method, except that it wakes up automatically if there is no wake-up for the notify or notifAll method within a specified period of time.
As for wait (long timeout,long nanos), it is intended to control the scheduling time more precisely. However, judging from the current version, this method does not seem to fully implement this function. Its source code (JDK1.8) is as follows:
Public final void wait (long timeout, int nanos) throws InterruptedException {if (timeout)
< 0) { throw new IllegalArgumentException("timeout value is negative"); } if (nanos < 0 || nanos >999999) {throw new IllegalArgumentException ("nanosecond timeout value out of range");} if (nanos > = 500000 | | (nanos! = 0 & & timeout = = 0) {timeout++;} wait (timeout);}
From the point of view of the source code, the nanosecond processing in JDK8 is only rounded, so it is still processed in milliseconds, and nanosecond precision may be used at some point in the future. Although JDK provides these three versions, in the end, it is implemented by calling the wait (long timeout) method, which is equivalent to wait (0), while wait (long timeout,int nanos) is also done through wait (long timeout) as can be seen from the above source code.
Let's demonstrate the use of the wait () method with a simple example:
Package com.paddx.test.concurrent; public class WaitTest {public void testWait () {System.out.println ("Start-"); try {wait (1000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("End-") } public static void main (String [] args) {final WaitTest test = new WaitTest (); new Thread (new Runnable () {@ Override public void run () {test.testWait ();}) .start ();}}
The intention of this code is simple: after the program is executed, let it pause for a second, and then execute. Run the above code to view the results:
Instead of outputting the result as expected, the Start-Exception in thread "Thread-0" > program throws an exception. You may wonder why an exception is thrown. And what is the IllegalMonitorStateException exception thrown? We can take a look at the description of IllegalMonitorStateException in JDK: Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor. The thread attempts to wait for the monitor of the object or to notify other threads that are waiting for the monitor, but does not have ownership of the corresponding monitor. In fact, this question is in the [issue 68] interviewer: are you familiar with concurrency? As mentioned in the article "talking about Synchronized and the principle of implementation", the wait method is a native method, whose underlying layer is done through an object called a monitor lock. So the reason why the above throws an exception is that the ownership of the monitor object is not obtained when the wait mode is called, so how do you get the ownership of the monitor object? The Synchronized keyword can only be used in Java. Modify the above code and add the Synchronized keyword: package com.paddx.test.concurrent; public class WaitTest {public synchronized void testWait () {/ / add the Synchronized keyword System.out.println ("Start-"); try {wait (1000);} catch (InterruptedException e) {e.printStackTrace () } System.out.println ("End-");} public static void main (String [] args) {final WaitTest test = new WaitTest (); new Thread (new Runnable () {@ Override public void run () {test.testWait ();}}) .start () }} now run the above code again, and you can see the expected effect: Start-End-, so, through this example, you should be very clear that the use of the wait method must be within the scope of synchronization, otherwise an IllegalMonitorStateException exception will be thrown. The purpose of the wait method is to block the current thread from waiting for the notify/notifyAll method to wake up, or to wake up automatically after waiting for the timeout. 2. Notify/notifyAll method has an understanding of the principle of wait method, notify method and notifyAll method are easy to understand. Since the wait method is implemented through the object's monitor object, as long as the notify/notifyAll method is called on the same object, you can wake up the waiting thread on the corresponding object monitor. The difference between notify and notifyAll is that the former wakes up only one thread on monitor and has no effect on other threads, while notifyAll wakes up all threads. It is easy to see the difference between the two in the following example: package com.paddx.test.concurrent The output of public class NotifyTest {public synchronized void testWait () {System.out.println (Thread.currentThread (). GetName () + ">) is as follows: Thread-0 Start-Thread-1 Start-Thread-2 Start-Thread-3 Start-Thread-4 Start-Thread-0 End- split line- -Thread-4 End-Thread-3 End-Thread-2 End-Thread-1 End- you can see from the result that only thread Thread-0 is awakened when the notify method is called But when notifyAll is called, all threads are awakened. Finally, there are two points to note: 1. When the wait method is called, the thread releases ownership of the monitor object. two。 A thread blocked by the wait method must meet both the following two conditions before it can be truly executed: the thread needs to be woken up (waking up during a timeout or calling notify/notifyll). After the thread wakes up, it needs to compete to the monitor. Third, sleep/yield/join method parsing above we have a clear understanding of the use and principle of wait and notify methods, now let's look at another set of methods of inter-thread cooperation. The most obvious difference between this set of methods and the above methods is that these methods are all in the Thread class, while the above three methods are in the Object class. As for why, you can think about it first. Now let's analyze the sleep/yield/join method one by one: 1. The function of the sleepsleep method is to pause the current thread for a specified time (milliseconds). The sleep method is the simplest method, which has been used in the above example and is easier to understand. The only thing to note is the difference between it and the wait method. The simplest difference is that the wait method relies on synchronization, while the sleep method can be called directly. The deeper difference is that the sleep method only temporarily relinquishes the execution of the CPU and does not release the lock. The wait method requires the lock to be released. Package com.paddx.test.concurrent; public class SleepTest {public synchronized void sleepMethod () {System.out.println ("Sleep start-"); try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("Sleep end-") } public synchronized void waitMethod () {System.out.println ("Wait start-"); synchronized (this) {try {wait (1000);} catch (InterruptedException e) {e.printStackTrace ();}} System.out.println ("Wait end-") } public static void main (String [] args) {final SleepTest test1 = new SleepTest (); for (int I = 0polii
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.