2014年4月30日星期三

Java_012:BLOCKED线程例子 (摘录+整理)

1. MyThread.java

public class MyThread implements Runnable {

    public void run() {
        synchronized (this) {
            for (int i = 0; i < 1; i--) {
                System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
            }
        }
    }

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        Thread ta = new Thread(t1, "A");
        Thread tb = new Thread(t1, "B");
        ta.start();
        tb.start();
    }
}

2. 线程A与线程B的thread dump
(1)线程A的状态是runnable:RUNNABE。
(2)线程B 的状态是waiting for monitor entry:BLOCKED。

"B" prio=5 tid=0x00007fb683944000 nid=0x6103 waiting for monitor entry [0x00000001127fb000]
   java.lang.Thread.State: BLOCKED (on object monitor)
at MyThread.run(MyThread.java:18)
- waiting to lock <0x00000007247b6220> (a MyThread)
at java.lang.Thread.run(Thread.java:744)

"A" prio=5 tid=0x00007fb6838be800 nid=0x5f03 runnable [0x00000001126f8000]
   java.lang.Thread.State: RUNNABLE
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:345)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
- locked <0x000000072482bd48> (a java.io.BufferedOutputStream)
at java.io.PrintStream.write(PrintStream.java:482)
- locked <0x00000007247b59a0> (a java.io.PrintStream)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
- locked <0x0000000724821340> (a java.io.OutputStreamWriter)
at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
at java.io.PrintStream.newLine(PrintStream.java:546)
- eliminated <0x00000007247b59a0> (a java.io.PrintStream)
at java.io.PrintStream.println(PrintStream.java:807)
- locked <0x00000007247b59a0> (a java.io.PrintStream)
at MyThread.run(MyThread.java:19)
- locked <0x00000007247b6220> (a MyThread)
at java.lang.Thread.run(Thread.java:744)

原因解释:
线程阻塞是指当前线程执行过程中,所需要的资源长时间等待却一直未能获取到,被容器的线程管理器标识为阻塞状态,可以理解为等待资源超时的线程。
这里线程B苦苦等待获取Monitor,企图lock对象<0x00000007247b6220>,但该对象一直被线程A牢牢locked <0x00000007247b6220>,因此经过一定时间,线程B被容器的线程管理器标识为BLOCKED。

没有评论: