当我尝试执行这段代码时,我得到的输出类似于12221121212121221212
. 当我将方法声明为synchronized
时,它不应允许其他线程接管控制权
package com.test;
public class TestProject extends Thread {
public void run() {
synchronized (this) {
for (int i = 0; i < 10; i++) {
System.out.print(getName());
}
}
}
public static void main(String[] args) throws InterruptedException {
TestProject myProject = new TestProject();
TestProject myProject1 = new TestProject();
myProject.setName("1");
myProject1.setName("2");
myProject.start();
myProacject1.start();
}
}
那么,如何更改代码以按顺序格式输出11111111112222222222或22222222221111111111 ?