如果我正确理解使用synchronized
word lock this
对象的方法,并且任何其他线程将在执行synchronized
方法时等待,并且任何其他方法关闭以执行,对象中的任何方法,对象锁定。
示例代码:
public class MainClass {
public static void main(String[] args) {
User user = new User();
user.setAge(10);
user.setData("data");
Thread thread = new Thread(new ChildThread(user));
thread.start();
PI.print(Thread.currentThread(), user.getData());
}
}
public class ChildThread implements Runnable {
private User user;
public ChildThread(User user) {
this.user = user;
}
@Override
public void run() {
Integer age = user.getAge();
PI.print(Thread.currentThread(), age.toString());
}
}
public class User {
private Integer age;
private String data;
public synchronized Integer getAge() {
try {
System.out.println("Blocked");
Thread.sleep(3000);
System.out.println("Stop sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public synchronized String getData() { //synchranized on the same object
return data;
}
public void setData(String data) {
this.data = data;
}
}
public class PI {
public static void print(Thread thread, String age) {
System.out.println("Name: " + thread.getName() + " res: " + age);
}
}
将输出下一个结果:
Blocked
Name: main res: data
Stop sleep
Name: Thread-0 res: 10
为什么'主要'线程不会在结束时执行另一个线程吗?