理论上 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);
}
}
我觉得你应该好好看看线程的东西。这个问题就是锁的问题。
thread1.start();
thread2.start();
这两句话呢是启动了两个线程,然后线程1调用out,线程2调用print。如果一个线程阻塞在那里,肯定是在等待锁。但是你的out方法执行结束之后,就把锁释放掉了,所以线程2也就执行了。这时候可能线程1还在等待,直到5秒结束。如果想要达到你想要的效果,就不应该在线程1里面执行sleep,而是应该在out方法里执行sleep,因为这样才能使线程1一直占有锁。