问题分析:正如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方式实现。

最新文章

  1. cocos2d-x创建项目
  2. This kind of launch is configured to open the Debug perspective when it suspends.
  3. CSS裁剪clip
  4. FineUI v4.0.3 (beta) 和 FineUI v3.3.3 发布了!
  5. 面试题:Integer和int的区别?在什么时候用Integer和什么时候用int
  6. iOS学习17之OC内存管理
  7. Java Messages Synchronous and Asynchronous
  8. HTML5与CSS3权威指南
  9. mysql+heartbeat+DRBD+LVS集群
  10. ServletContext对象--三大域对象
  11. MSSQL Server查询优化方法(转)
  12. [Swift]LeetCode491. 递增子序列 | Increasing Subsequences
  13. assert()函数总结 (转)
  14. ionic3样例应用
  15. Caused by: Java.lang.NoSuchMethodError: javax.persistence.JoinColumn.foreignKey()Ljavax/persistence/ForeignKey;
  16. easyui combobox 去空格事件 去掉,结果输入空格体验不畅的感觉,让combobox能够输入空格
  17. MyCAT简易入门 (Linux)
  18. php调用python脚本
  19. Screen Monitors
  20. Throwable、Error、Exception、RuntimeException 区别

热门文章

  1. Celery:routing
  2. java开发手册-总结与补充
  3. Xshell设置全局配色
  4. django中使用AJAX时如何获取表单参数(按钮携带参数)
  5. 微信小程序转义解析渲染html
  6. c风格的字符串
  7. 如何更改Scratch3.0的LOGO
  8. ArcGIS操作技巧——怎样把地图放到PPT中,并且进行编辑?
  9. Oracle锁表与解锁 对象锁与解锁
  10. java代码操作word模板并生成PDF