Some methods of Java thread state correlation

Source: Internet
Author: User

http://blog.jrwang.me/2016/java-thread-states/Posted in 2016-07-23

In Java multithreaded programming, the Methods of Sleep (), interrupt (), wait (), notify () are very basic and common methods. These methods change the state of the running Java threads, and the correct understanding of these methods is the basic requirement of mastering Java concurrency Programming.

The state of the Java thread

Let's talk about the state of threads in Java. In Java, the state of the thread and the state of the threads in the underlying operating system are not one by one corresponding relationships, and what we can see is the state exposed at the JVM virtual machine level.

The state of the threads in Java is defined in the internal enumeration class of thread, there,,,, and Thread.State NEW RUNNABLE BLOCKED WAITING TIMED_WAITING TERMINATED This six class state.

In the official Java documentation, "A thread in the runnable state is executing in the Java Virtual machine but it may be waiting for other R Esources from the operating system such as processor. "That is, the RUNNABLE thread in the state is executing in the Java virtual machine in the JVM virtual machine, but it may be waiting for other resources from the operating system, such as processing Manager In fact, if a thread waits for a blocking I/O operation, its state is also RUNNABLE .

If a thread blocks (the Synchronized keyword) during the acquisition of an object lock, it is in the BLOCKED state. Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state was waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized Block/method after calling Object.wait.

And if the following three types of methods are called, the thread is in WAITING state and waits for other threads to wake it up:

    • Object.waitWith no timeout
    • Thread.joinWith no timeout
    • LockSupport.park

If you are Lock.lock() waiting to acquire a lock through a method, you are also in the WAITING state. Because the Lock implementation of the interface is based on AQS, the blocking operations in AQS are implemented based on the LockSupport tool class.

TIMED_WAITINGThe state and WAITING state are similar, except that waiting for a timeout event occurs, and the following methods cause the thread to enter that state:

    • Thread.sleep
    • Object.waitWith timeout
    • Thread.joinWith timeout
    • LockSupport.parkNanos
    • LockSupport.parkUntil

Similarly, a method with a timeout Lock.tryLock(long time, TimeUnit unit) will enter that state when it waits for a lock to be acquired.

Usually, at the operating system level, there are five types of threads in the state, the transition relationship of the State can refer to the following diagram.

As you can see, the thread state described in the JVM is not the same as the thread state of the OS plane. The JVM RUNNABLE is actually contained in, RUNNING READY , and part of the WAITING state, while the JVM WAITING , and in fact, is TIMED_WAITING BLOCKED WAITING A more detailed division of the remainder of the case.

sleepVswait

sleep(long)And wait() methods allow the thread to pause execution and yield the current processor resource. However, there are some essential differences between the two methods.

sleep(long)A method is a static method defined in a class that causes the Thread thread to sleep (that is, to temporarily stop running) for a specified amount of time, enter the state, and TIMED_WAITING then re-enter the state when it times out RUNNABLE . sleep()method retains the running state of the current thread, and the lock resources held by the thread are not freed.

wait()method is defined on the method Object , and any one class Object inherits the method from the class. The method ( obj.wait() ) is called if the current thread acquires a lock on the object ( obj ). When the method is called, the thread enters the WAITING state, releasing the lock on the object it holds, and the JVM places the thread in the object's waiting queue. The wait() method needs to be obj.notify() awakened by or obj.notifyAll() , notify() and notifyAll() one or all of the threads in the object's wait queue will be moved into the object's synchronization queue to compete for the lock of the object, which is returned from the method when the lock is acquired wait() . Simply put, the wait() method frees the lock held by the thread, waits notify() or notifyAll() wakes, and wait() returns from the method indicating that the thread has re-acquired the object lock.

wait(long)is wait() an overloaded version, the effect is basically the same, just wait(long) enter TIMED_WAITING the state, timeout can also be awakened.

interrupt

Many people see the interrupt() method that the "interrupt" thread is not just to let the thread stop. In fact, interrupt() this is not the effect of the method's implementation, it is interrupt() more like sending a signal that alters the thread's identity bit attribute (interrupt identifier), which is not deterministic for how the signal is handled (there can be different processing logic). Many times the calling interrupt() method is not just to stop the thread, but to keep the thread running.

The effects in the Java documentation are interrupt() listed in four scenarios:

If This thread was blocked in an invocation of the wait (), wait (long), or wait (long, int) methods of the O Bject class, or of the join (), join (long), join (long, int), sleep (long), or sleep (long, int), methods of this class, then Its interrupt status would be cleared and it would receive an interruptedexception.

If This thread was blocked in an I/O operation upon an interruptiblechannel then the channel would be closed, the thread ' s interrupt status would be set, and the thread would receive a closedbyinterruptexception.

If This thread was blocked in a Selector then the thread ' s interrupt status would be set and it would return immediately F Rom the selection operation, possibly with a non-zero value, just as if the selector ' s wakeup method were invoked.

If None of the previous conditions hold and this thread ' s interrupt status would be set.

The first three scenarios describe the fact that if a thread is in a waiting state or is blocking a resource, the interrupt() method will cause the thread to go out of this state and continue. The fourth scenario is that if the thread is executing properly, interrupt() the effect is to set the interrupt state of the thread, and as for how to handle this state, you can choose to ignore it or handle it on demand.

A method can be used isInterrupted() to test the state of the interrupt identity of the current thread, and the static method Thread.interrupted() can determine whether the currently threaded state is in the interrupt status, and also clears the current interrupt state. Typically used Thread.interrupted() to reset the interrupt identity. In the first case we can see that the InterruptedException interrupt identity is cleared before it is thrown, and therefore the call in the exception handling isInterrupted() returns FALSE.

If the thread calls sleep(long) the method to sleep for a very long time, and now wants to wake it up, you can call the interrupt() method. Note that the exception in the method declaration, which is visible, is wait() sleep() not a call to throw an join() exception, but rather, in the process of waiting, the interrupt() wait() sleep() join() Calling method causes it to interrupt() return from the wait state and receives an InterruptedException exception, The control logic is then given to the exception-handling statement.

wait()when a thread waiting in a method is interrupted, as with notify() wake, the lock on the object must be re-acquired to be returned from the method, rather than being returned immediately and into exception handling. The following example simply verifies:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21st
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
PublicClassInterruptdemo {
PublicStaticvoidMain(string[] args)Throws interruptedexception{
WN WN =New WN ();

Thread T1 =New Thread (New Runnable () {
@Override
PublicvoidRun() {
WN.M1 ();
}
});
T1.setname ("Thread 1");

Thread t2 =New Thread (New Runnable () {
@Override
PublicvoidRun() {
WN.M2 ();
}
});
T2.setname ("Thread 2");

T1.start ();
T2.start ();

Thread.Sleep (1000L);
System.out.println ("Call Interrupt @" + system.currenttimemillis ());
T1.interrupt ();
}

StaticClassWN {
Private Object o =New Object ();

PublicvoidM1() {
Synchronized (o) {
System.out.println (Thread.CurrentThread (). GetName () +"Get lock @"
+ System.currenttimemillis ());
try {
O.wait ();
System.out.println ("Return from Wait () @" + system.currenttimemillis ());
}catch (Interruptedexception e) {
System.out.println ("Interrupted during obj.wait () @" + System
. Currenttimemillis ());
}
}
}

Publicvoidm2 () {
synchronized (o) {
System.out.println (Thread.CurrentThread (). GetName () + "Get lock @"
try {
Thread.Sleep ( 10000L);
System.out.println (Thread.CurrentThread (). GetName () + "release lock @" +
System.currenttimemillis ());
} catch (interruptedexception e) {
E.printstacktrace ();
}
}

Results of the output:

1
2
3
4
5
1 Get lock @1471189560880
2 Get lock @1471189560880
Call Interrupt @1471189561880
2 release lock @1471189570881
Interrupted during obj.wait () @1471189570881

As you can see, only thread 2 releases the lock after it has been freed (Threads 2 is freed up to regain it) before it is wait() returned from the method.

Yield

yield()The method is a Thread static method of the class and is also used to assign the CPU resources that the current thread consumes. sleep(long)Unlike the method, the sleep(long) thread enters the WAITING state and at least waits for the time-out to arrive before it executes again, and the yield() method is from the RUNNING entry READY state (this is the operating system level, which is exposed RUNNABLE in the JVM status), so it is very likely that it will be scheduled to continue running immediately.

A hint to the scheduler, the current thread was willing to yield it current use of a processor. The scheduler is a free-to-ignore this hint.

From the representations in the document, the yield() method sleep(long) is more dependent on the scheduling of the system than the method. This method is not often used.

-eof-

Some methods of Java thread state correlation

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.