Java用wait和notify实现线程协作

编写一个应用程序,除了主线程外,还有两个子线程。两个子线程对同一个数据操作,其中一个线程负责对该数据做递增操作,一个线程负责对该线程做递减操作。当这个数据小于0的话,递减操作等待,当这个数据大于100的话,递增操作等待。

import java.lang.*;
public class Demo{
    private int a = 0;

    public synchronized void add(){
        ++a;

        if(a > 100){
            try{
                this.wait();

            }catch(Exception e){
                e.printStackTrace();
            }
        }else{
            System.out.println(Thread.currentThread().getName()+":"+a);
        }
        this.notify();
    }

    public synchronized void delete(){
        --a;
        if(a < 0){
            try{
                this.wait();

            }catch(Exception e){
                e.printStackTrace();
            }
        }else{
            System.out.println(Thread.currentThread().getName()+":"+a);
        }
        this.notify();
    }
    public static void main(String[] args) {
        Demo dm = new Demo();
        new Thread(){
            public void run(){
                while(true){
                    dm.add();
                }
            }
        }.start();

        new Thread(){
            public void run(){
                while(true){
                    dm.delete();
                }
            }
        }.start();
    }

}

你可能感兴趣的:(java)