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是唤醒多个
本文深入探讨了Java多线程编程中的wait与notify机制,详细解释了它们的作用、使用方式以及如何在synchronized块中正确应用,确保线程安全与高效执行。
1821

被折叠的 条评论
为什么被折叠?



