欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

初始化为0的变量,两个线程对它操作,一个加一 一个减一

程序员文章站 2024-01-09 23:47:28
...
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ShareData {
    int number;
    Lock lock  = new ReentrantLock();
    Condition condition = lock.newCondition();
    public void increate(){
        try {
            lock.lock();
                while(number!=0){
                    condition.await();
                }
                number++;
                System.out.println(Thread.currentThread().getName()+"\t"+number);
                condition.signal();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }

    }
    public void decreate(){
        try {
            lock.lock();
                // 1 判断
                while(number!=1){
                    // 线程等待
                    condition.await();
                }
                // 2 do it
                number--;
                System.out.println(Thread.currentThread().getName()+"\t"+number);
                //3  线程唤醒
                condition.signal();

        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        ShareData sd = new ShareData();


        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                sd.increate();
            }
        },"thread A").start();


        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                sd.decreate();
            }
        },"thread B").start();


    }
}

thread A	1
thread B	0
thread A	1
thread B	0
thread A	1
thread B	0
thread A	1
thread B	0
thread A	1
thread B	0

Process finished with exit code 0

 

相关标签: java