Skip to content

对于4.3.1的blockedTest的输出结果的疑问 #147

@WFKhitsz

Description

@WFKhitsz

章节

4.3.1的第一个blockedTest代码块

相关截图或文字

你们这里说 “测试方法的main线程只保证了a,b两个线程调用start()方法(转化为RUNNABLE状态),还没等两个线程真正开始争夺锁,就已经打印此时两个线程的状态(RUNNABLE)了。”

疑问
我本地代码跑出来的结果是:
a:RUNNABLE
b:BLOCKED

我很疑惑,线程的执行应该是没有顺序的,主线程开启了A,B线程后,就不知道到在打印语句之前到底执行了那个线程的代码,可是您的描述是打印语句一定会先执行,这是为什么呢?

下面是我的测试代码:

public class Test {
public static void main(String[] args) {
Test test = new Test();
test.blockedTest();
}

public void blockedTest() {

    Thread a = new Thread(new Runnable() {
        @Override
        public void run() {
            testMethod();
        }
    }, "a");
    Thread b = new Thread(new Runnable() {
        @Override
        public void run() {
            testMethod();
        }
    }, "b");

    a.start();
    b.start();
    System.out.println(a.getName() + ":" + a.getState()); // 输出?
    System.out.println(b.getName() + ":" + b.getState()); // 输出?
}

// 同步方法争夺锁
private synchronized void testMethod() {
    try {
        Thread.sleep(2000L);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions