多线程之线程间通信

原创
2020/03/12 17:17
阅读数 91

1、案例

class NumberHolder {
    private int number;

    public synchronized void increase() {
        if (0 != number) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 能执行到这里说明已经被唤醒
        // 并且number为0
        number++;
        System.out.print(number+"-");

        // 通知在等待的线程
        notify();
    }

    public synchronized void decrease() {
        if (0 == number) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 能执行到这里说明已经被唤醒
        // 并且number不为0
        number--;
        System.out.print(number+"-");
        notify();
    }
}

 

class IncreaseThread extends Thread {
    private NumberHolder numberHolder;

    public IncreaseThread(NumberHolder numberHolder) {
        this.numberHolder = numberHolder;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; ++i) {
            // 进行一定的延时
            try {
                Thread.sleep((long) Math.random() * 10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 进行增加操作
            numberHolder.increase();
        }
    }
}

 

class DecreaseThread extends Thread {
    private NumberHolder numberHolder;

    public DecreaseThread(NumberHolder numberHolder) {
        this.numberHolder = numberHolder;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; ++i) {
            // 进行一定的延时
            try {
                Thread.sleep((long) Math.random() * 10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 进行减少操作
            numberHolder.decrease();
        }
    }
}

 

public class Main {
    public static void main(String[] args) throws InterruptedException {
        NumberHolder numberHolder = new NumberHolder();

        Thread t1 = new IncreaseThread(numberHolder);
        Thread t2 = new DecreaseThread(numberHolder);
        // Thread t3 = new DecreaseThread(numberHolder);
        // Thread t4 = new DecreaseThread(numberHolder);

        t1.start();
        t2.start();
        // t3.start();
        // t4.start();
    }
}

 

2、分析

 

此案例

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部