简单wait(),notify()方法

1.两个类
public class Name{


public static void main(String[] args) throws InterruptedException {
User user=new User();
Nice nice =new Nice(user);
Ki ki =new Ki(user);
new Thread(nice).start();
new Thread(ki).start();
}

}

class Nice extends Thread{
Object object;
public Nice(Object object){
this.object=object;
}

@Override
public void run() {
synchronized (object){
try {
System.out.println("aaaaaaaaaaaaa");
object.wait();
System.out.println("bbbbbbbbbbbbbbbb");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class Ki extends Thread{

Object object;

public Ki(Object object){
this.object=object;
}

@Override
public void run() {
synchronized (object) {
object.notify();
}
}
}
2.一个类,两个方法

public class Name{


public static void main(String[] args) throws InterruptedException {
User user=new User();
Nice nice =new Nice(user);
nice.food();
nice.good();
}

}

class Nice{
Object object;
public Nice(Object object){
this.object=object;
}
public void food(){
Runnable runnable =new Runnable() {
@Override
public void run() {
synchronized (object){
try {
System.out.println("aaaaaaaaaaaaaaa");
object.wait();
System.out.println("bbbbbbbbbbbbbbbbbbbb");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};

Thread thread =new Thread(runnable);
thread.start();
}

public void good(){
Runnable runnable2 =new Runnable() {
@Override
public void run() {
synchronized (object){
object.notify();
}
}
};
Thread thread =new Thread(runnable2);
thread.start();
}


}

3.注意:
wait(),notify()要和synchronized一起使用,要获取到锁





posted @ 2018-11-23 16:18  山神笔记  阅读(237)  评论(0编辑  收藏  举报