日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2023/12/18 36 如意码农
生活随笔 收集整理的這篇文章主要介紹了 Java-JUC(十三):现在有两个线程同时操作一个整数I,做自增操作,如何实现I的线程安全性? 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題分析:正如i在多線程中如果想實現i的多線程操作,必須i要使用volitle來保證其內存可見性,但是i++自增操作不具備原子性操作,因此需要對i++這段代碼確保其原子性操作即可。

方案1:

使用ReetranLock實現i++的原子性操作。

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:

使用Semaphore實現i++的原子性操作。

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);
}

當然也可以選擇sychronized方式實現。

總結

以上是生活随笔為你收集整理的Java-JUC(十三):现在有两个线程同时操作一个整数I,做自增操作,如何实现I的线程安全性?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。