-
Notifications
You must be signed in to change notification settings - Fork 618
Open
Description
章节
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
Labels
No labels