理论上 synchronized 是持有的对象级的锁。那么就应该在thread1执行完task.out()后,休眠5s后thread2才可以执行 task.print()。
为什么我在运行这段代码时同时出来了结果?
如果我的代码是错误的。请给出正确的代码。谢谢。
public class Run {
public static void main(String[] args) {
final Task task = new Task();
Thread thread1 = new Thread(new Runnable() {
public void run() {
task.out();
try {
Thread currentThread = Thread.currentThread();
currentThread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "thread1");
Thread thread2 = new Thread(new Runnable() {
public void run() {
task.print();
}
}, "thread2");
thread1.start();
thread2.start();
}
}
package thread;
public class Task {
public synchronized void out() {
String name1 = "method out()" + Thread.currentThread().getName();
System.out.println(name1);
}
public synchronized void print() {
String name1 = "method print()" + Thread.currentThread().getName();
System.out.println(name1);
}
}