juc_lock

ここに画像の説明を挿入します

1つはjucではなく、もう1つはjucです

class Data2{
    private int number = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment() throws Exception{
        lock.lock();
        try {
            while (number != 0){
                condition.await();
            }
            number ++;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
    public void decrement() throws Exception{
        lock.lock();
        try {
            while (number == 0){
                condition.await();
            }
            number --;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}
    @Test
    public void test1(){
        Data2 data2 = new Data2();
        new Thread((()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data2.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }),"A").start();
        new Thread((()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data2.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }),"B").start();
    }

ここに画像の説明を挿入します

おすすめ

転載: blog.csdn.net/qq_43141726/article/details/114281794