代码:
package main;
public class TestWait {
public static void main(String[] args) {
TestWait tw = new TestWait();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
tw.call2(5000);
System.out.println(Thread.currentThread().getName()+"-exit");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
tw.call2(1);
System.out.println(Thread.currentThread().getName()+"-exit");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t2");
t1.start();
t2.start();
}
public synchronized void call2(long timeout) throws InterruptedException {
System.out.println(Thread.currentThread().getName()+"-come in synchronized method");
wait(timeout);
System.out.println(Thread.currentThread().getName()+"-exit synchronized method");
}
}
测试结果:
t2-come in synchronized method
t1-come in synchronized method
t2-exit synchronized method
t2-exit
t1-exit synchronized method
t1-exit
而 synchronized(tw){} 代码块的方法,只能1个线程进入; 代码略。 二者有什么区别?
求大神指点