Java-JUC(十三):现在有两个线程同时操作一个整数I,做自增操作,如何实现I的线程安全性?
2024-09-05 18:58:47
问题分析:正如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方式实现。
最新文章
- cocos2d-x创建项目
- This kind of launch is configured to open the Debug perspective when it suspends.
- CSS裁剪clip
- FineUI v4.0.3 (beta) 和 FineUI v3.3.3 发布了!
- 面试题:Integer和int的区别?在什么时候用Integer和什么时候用int
- iOS学习17之OC内存管理
- Java Messages Synchronous and Asynchronous
- HTML5与CSS3权威指南
- mysql+heartbeat+DRBD+LVS集群
- ServletContext对象--三大域对象
- MSSQL Server查询优化方法(转)
- [Swift]LeetCode491. 递增子序列 | Increasing Subsequences
- assert()函数总结 (转)
- ionic3样例应用
- Caused by: Java.lang.NoSuchMethodError: javax.persistence.JoinColumn.foreignKey()Ljavax/persistence/ForeignKey;
- easyui combobox 去空格事件 去掉,结果输入空格体验不畅的感觉,让combobox能够输入空格
- MyCAT简易入门 (Linux)
- php调用python脚本
- Screen Monitors
- Throwable、Error、Exception、RuntimeException 区别