package www.td;
public class ThreadDemo {
public static void main(String[] args) {
System.out.println("主线程");
NotifiThread nt=new NotifiThread();
nt.start();
synchronized (nt) {
try {
System.out.println("等待nt线程执行完毕。。");
nt.wait();
System.out.println("xxxxxxxx");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class NotifiThread extends Thread{
@Override
public void run() {
//1、synchronized (this) {
synchronized (this) {
try {
Thread.sleep(2000);
System.out.println("子线程");
notify();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//notify();
public class ThreadDemo {
public static void main(String[] args) {
System.out.println("主线程");
NotifiThread nt=new NotifiThread();
nt.start();
synchronized (nt) {
try {
System.out.println("等待nt线程执行完毕。。");
nt.wait();
System.out.println("xxxxxxxx");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class NotifiThread extends Thread{
@Override
public void run() {
//1、synchronized (this) {
synchronized (this) {
try {
Thread.sleep(2000);
System.out.println("子线程");
notify();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//notify();
//}
}
}
wait与notify的使用在synchronized ()块中,如果没有回报java.lang.IllegalMonitorStateException异常
notify wait 为什么放在synchronized块中 why?
答:wait 是释放锁的,notify是唤醒锁的,而锁有是在synchronized()块中。
notifyAll是唤醒多个