import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleepAndWait {
public static void main(String[] args) {
new
Thread1().start();
try
{
Thread.sleep(100);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
new
Thread2().start();
}
}
class Thread1 extends Thread{
private void sout(String s){
System.out.println(s+
" "
+
new
SimpleDateFormat(
"HH:mm:ss:SS"
).format(
new
Date()));
}
@Override
public void run() {
sout(
"enter Thread1.run"
);
synchronized (TestSleepAndWait.class){
sout(
"Thread1 is going to wait"
);
try
{
TestSleepAndWait.class.wait();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
sout(
"after waiting, thread1 is going on"
);
sout(
"thread1 is over"
);
}
}
}
class Thread2 extends Thread{
private void sout(String s){
System.out.println(s+
" "
+
new
SimpleDateFormat(
"HH:mm:ss:SS"
).format(
new
Date()));
}
@Override
public void run() {
sout(
"enter Thread2.run"
);
synchronized (TestSleepAndWait.class){
sout(
"Thread2 is going to notify"
);
TestSleepAndWait.class.notify(); 这里只能使用持有锁TestSleepAndWait.class
sout(
"thread2 is going to sleep 10ms"
);
try
{
Thread.sleep(10);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
sout(
"after sleeping, thread2 is going on"
);
sout(
"thread2 is over"
);
}
}
}