zoukankan      html  css  js  c++  java
  • 简单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一起使用,要获取到锁





  • 相关阅读:
    hdu 2137
    hdu 2059
    hdu 2175
    hdu 1297
    hdu 1702
    hdu 1212
    hdu 1397
    [转]常见的碱性食品有哪些?
    [转]C#反射
    每个人都有自己的未来
  • 原文地址:https://www.cnblogs.com/shanshen/p/10008266.html
Copyright © 2011-2022 走看看