In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail the example analysis of thread states and methods in java. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.
I. the state of the thread
Before we formally learn the specific methods in the Thread class, let's take a look at the state of the thread, which will help us understand the methods in the Thread class later.
A thread goes through several states from creation to final death. Generally speaking, a thread includes the following states: create (new), ready (runnable), run (running), blocked (blocked), time waiting, waiting, and dead.
When a new thread is needed to perform a subtask, a thread is created. But after the thread is created, it will not enter the ready state immediately, because the thread needs some conditions to run (for example, the program counter, the Java stack, and the local method stack are all private to the thread, so you need to allocate a certain amount of memory space for the thread). Only when all the conditions needed for the thread to run have been met, the thread will enter the ready state.
When a thread is ready, it doesn't mean you can get the CPU execution time immediately. Maybe CPU is doing something else at this time, so it has to wait. When the CPU execution time is obtained, the thread actually enters the running state.
When a thread is in a running state, there may be several reasons why the current thread does not continue to run, such as the user actively lets the thread sleep (sleep for a certain period of time before re-executing), the user actively lets the thread wait, or is blocked by the synchronization block, which corresponds to multiple states: time waiting (sleeping or waiting for a certain event), waiting (waiting to be awakened), blocked (blocking).
When a thread dies due to a sudden interruption or the completion of a subtask.
The following figure describes the state of a thread from creation to extinction:
In some tutorials, blocked, waiting, and time waiting are collectively referred to as blocking state, but here I want to associate the state of the thread with the method calls in Java, so separate the waiting and time waiting states.
2. Methods in Thread class
By looking at the source code of the java.lang.Thread class, you can see:
The Thread class implements the Runnable interface. In the Thread class, there are some key attributes. For example, name is the name of the Thread, which can be specified through the parameters in the constructor of the Thread class. Priority represents the priority of the thread (the maximum value is 10, the minimum value is 1, and the default value is 5). Daemon indicates whether the thread is a daemon thread, and target represents the task to be executed.
Here are the methods commonly used in the Thread class:
Here are several methods that relate to the running state of a thread:
1) start method
Start () is used to start a thread, and when the start method is called, the system starts a new thread to perform user-defined subtasks, during which resources are allocated to the corresponding thread.
2) run method
The run () method does not need to be called by the user. When a thread is started through the start method, and when the thread gets the CPU execution time, it goes into the run method body to perform the specific task. Note that inheriting the Thread class must override the run method to define the specific task to be performed in the run method.
3) sleep method
There are two overloaded versions of the sleep method:
Sleep (long millis) / / Parameter is millisecond sleep (long millis,int nanoseconds) / / the first parameter is millisecond, and the second parameter is nanosecond
Sleep is the equivalent of putting threads to sleep, handing over CPU, and letting CPU perform other tasks.
If you need to pause the currently executing thread for a while and enter a blocking state, you can do so by calling the static sleep () method of the Thread class.
When the current thread calls the sleep () method to enter the blocking state, the thread will not get the opportunity to execute during its sleep time, even if there are no other executable threads in the system, the thread in sleep () will not execute, so the sleep () method is often used to suspend the execution of the program.
It is important to note, however, that the sleep method does not release the lock, which means that if the current thread holds a lock on an object, no other thread can access the object even if the sleep method is called. Take a look at the following example:
Public class Test {private int i = 10; private Object object = new Object (); public static void main (String [] args) throws IOException {Test test = new Test (); MyThread thread1 = test.new MyThread (); MyThread thread2 = test.new MyThread (); thread1.start (); thread2.start () } class MyThread extends Thread {@ Override public void run () {synchronized (object) {iSleep; System.out.println ("I:" + I); try {System.out.println ("Thread" + Thread.currentThread (). GetName () + "go to sleep") Thread.currentThread (). Sleep (10000);} catch (InterruptedException e) {/ / TODO: handle exception} System.out.println ("thread" + Thread.currentThread (). GetName () + "sleep end"); iSleep; System.out.println ("I:" + I) }
Output result:
As you can see from the output above, when Thread-0 goes to sleep, Thread-1 does not perform specific tasks. Only when the Thread-0 has finished executing, when the Thread-0 releases the object lock, does the Thread-1 begin execution.
Note that if the sleep method is called, the InterruptedException exception must be caught or thrown to the upper layer. When the thread's sleep time expires, it may not be executed immediately, because CPU may be performing other tasks at this time. So calling the sleep method is equivalent to putting the thread into a blocking state.
4) yield method
The yield () method is somewhat similar to the sleep () method, which is also a static method provided by the Thread class. It can also pause the currently executing thread, but it does not block the thread, it just puts the thread into a ready state. That is, to pause the current thread and reschedule the system's thread scheduler, it is entirely possible that when a thread calls the yield () method to pause, the thread scheduler schedules it to execute again.
Calling the yield method causes the current thread to hand over CPU permissions and CPU to execute other threads. Similar to the sleep method, it also does not release the lock. However, yield cannot control the specific time when the CPU is handed over, and when a thread calls the yield () method, only threads in the ready state with the same priority as or higher than the current thread will get the opportunity to execute.
Note that calling the yield method does not put the thread into a blocking state, but rather puts the thread back into the ready state, which just waits for the CPU execution time to be regained, unlike the sleep method.
5) join method
There are three overloaded versions of the join method:
Join () join (long millis) / / Parameter is millisecond join (long millis,int nanoseconds) / / the first parameter is millisecond, and the second parameter is nanosecond
If the thread.join method is called in a main thread, the main method waits for the thread to finish execution or wait for a certain amount of time. If you are calling the no-parameter join method, wait for the thread execution to finish, and if you are calling the join method with a specified time parameter, wait for some event.
Look at the following example:
Public class Test {public static void main (String [] args) throws IOException {System.out.println ("enter thread" + Thread.currentThread (). GetName ()); Test test = new Test (); MyThread thread1 = test.new MyThread (); thread1.start (); try {System.out.println ("thread" + Thread.currentThread (). GetName () + "wait") Thread1.join (); System.out.println ("Thread" + Thread.currentThread (). GetName () + "continue execution");} catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace () }} class MyThread extends Thread {@ Override public void run () {System.out.println ("enter thread" + Thread.currentThread () .getName ()); try {Thread.currentThread () .sleep (5000) } catch (InterruptedException e) {/ / TODO: handle exception} System.out.println ("Thread" + Thread.currentThread () .getName () + "execution completed");}
Output result:
As you can see, when the thread1.join () method is called, the main thread waits and then waits for thread1 to finish execution before continuing.
In fact, calling the join method calls the wait method of Object, which can be seen by looking at the source code:
The wait method puts the thread into a blocking state, releases locks held by the thread, and relinquishes CPU execution permissions.
Because the wait method causes the thread to release the object lock, the join method also causes the thread to release the lock held on an object. The specific use of wait methods is given in later articles.
6) interrupt method
Interrupt, as its name implies, means to interrupt. Calling the interrupt method alone causes a thread in the blocking state to throw an exception, that is, it can be used to interrupt a thread in the blocking state; in addition, the running thread is stopped through the interrupt method and the isInterrupted () method.
Let's look at an example:
Public class Test {public static void main (String [] args) throws IOException {Test test = new Test (); MyThread thread = test.new MyThread (); thread.start (); try {Thread.currentThread (). Sleep (2000);} catch (InterruptedException e) {} thread.interrupt () } class MyThread extends Thread {@ Override public void run () {try {System.out.println ("sleep"); Thread.currentThread () .sleep (10000); System.out.println ("sleep finished");} catch (InterruptedException e) {System.out.println ("get interrupt exception") } System.out.println ("run method execution completed");}
Output result:
As you can see here, you can interrupt a thread that is in a blocked state through the interrupt method. So can you interrupt a thread that is in a non-blocking state? Look at the following example:
Public class Test {public static void main (String [] args) throws IOException {Test test = new Test (); MyThread thread = test.new MyThread (); thread.start (); try {Thread.currentThread (). Sleep (2000);} catch (InterruptedException e) {} thread.interrupt () } class MyThread extends Thread {@ Override public void run () {int I = 0; while (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.