public class Test {
public static void main(String[] args) throws Exception {
System.out.println("start");
Thread.sleep(100000);
System.out.println("end");
}
}
通过Java VisualVM打印线程dump可以看到此线程处于TIMED_WAITING状态:
...
"main" #1 prio=5 os_prio=0 tid=0x00000000055b3800 nid=0x4e8c waiting on condition [0x000000000558f000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at Test.main(Test.java:4)
Locked ownable synchronizers:
- None
...
2.2 等待
调用wait,join这些不加时间参数的情况就会进入等待,表示一直等待直到被触发继续执行。
public class Test {
public static void main(String[] args) throws Exception {
Thread1 t = new Thread1();
t.start();
t.join();
}
static class Thread1 extends Thread {
@Override
public void run() {
System.out.println("start");
try {
Thread.sleep(100000);
} catch (InterruptedException e) {}
System.out.println("end");
}
}
}
...
"Thread-0" #11 prio=5 os_prio=0 tid=0x0000000020bf7000 nid=0x4f94 waiting on condition [0x000000002189f000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at Test$Thread1.run(Test.java:13)
Locked ownable synchronizers:
- None
...
"main" #1 prio=5 os_prio=0 tid=0x0000000004f63800 nid=0x431c in Object.wait() [0x0000000004eef000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x000000076b6e0898> (a Test$Thread1)
at java.lang.Thread.join(Unknown Source)
- locked <0x000000076b6e0898> (a Test$Thread1)
at java.lang.Thread.join(Unknown Source)
at Test.main(Test.java:5)
Locked ownable synchronizers:
- None
...
下面演示wait方法导致的等待状态:
public class Test {
public static int i = 0;
public static void main(String[] args) throws Exception {
Thread1 t = new Thread1();
t.start();
synchronized (t) {
System.out.println("等待子线程");
t.wait();
}
System.out.println("主线程结束");
}
static class Thread1 extends Thread {
@Override
public void run() {
synchronized (this) {
for (int i = 0; i < 10; i++) {
try {
System.out.println(i);
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
notify();
}
}
}
}
通过线程堆栈观察,主线程同样处于等待WAITING状态:
...
"main" #1 prio=5 os_prio=0 tid=0x0000000005983800 nid=0xb54 in Object.wait() [0x00000000058df000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x000000076b6e0aa8> (a Test$Thread1)
at java.lang.Object.wait(Unknown Source)
at Test.main(Test.java:8)
- locked <0x000000076b6e0aa8> (a Test$Thread1)
Locked ownable synchronizers:
- None
...
2.3 阻塞
public class Test {
public static void main(String[] args) throws Exception {
Thread1 t = new Thread1();
t.start();
test();
}
static class Thread1 extends Thread {
@Override
public void run() {
test();
}
}
static synchronized void test() {
System.out.println(Thread.currentThread().getName() + " -- start");
try {
Thread.sleep(100000);
} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + " -- end");
}
}