Java-JUC(十三):现在有两个线程同时操作一个整数I,做自增操作,如何实现I的线程安全性?

方案1:

private static volatile int i=0;
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch=new CountDownLatch(2);
        Lock lock=new ReentrantLock();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    lock.lock();
                    i++;
                }finally{
                    lock.unlock();
                    countDownLatch.countDown();
                }
            }
        },"Thread-1");
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    lock.lock();
                    i++;
                }finally{
                    lock.unlock();
                    countDownLatch.countDown();
                }
            }
        },"Thread-2");
        thread1.start();
        thread2.start();
        countDownLatch.await();

        System.out.println(i);
    }

方案2:

private static volatile int i = 0;

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        Semaphore semaphore = new Semaphore(1);
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
                semaphore.release();
                countDownLatch.countDown();
            }
        }, "Thread-1");
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
                semaphore.release();
                countDownLatch.countDown();
            }
        }, "Thread-2");
        thread1.start();
        thread2.start();
        countDownLatch.await();

        System.out.println(i);
    }

猜你喜欢

转载自www.cnblogs.com/yy3b2007com/p/11319038.html