public class SyncronizedTest {

    private int value = 1;
private AtomicInteger value1 = new AtomicInteger(1);
private Lock lock = new ReentrantLock(); //sycronized
public synchronized int getValue() {
return value ++ ;
} //jdk自带原子操作
public int getValue1() {
return value1.getAndIncrement();
} //lock
public int getValue2() {
lock.lock();
int a = value ++ ;
lock.unlock();
return a;
} public static void main(String[] args) { //此处必须使用同一个实例对象,因为synchronized锁此处针对的是对象,如果实例化2个对象相当于每个对象有一把锁
SyncronizedTest syncronizedTest = new SyncronizedTest();
long startTime = System.currentTimeMillis(); Runnable runnable = () -> {
for(int i = 0; i < 100; i ++){
System.out.println(Thread.currentThread().getName() + ",值:" + syncronizedTest.getValue());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread1 = new Thread(runnable);
thread1.start();
Thread thread2 = new Thread(runnable);
thread2.start();
Thread thread3 = new Thread(runnable);
thread3.start();
Thread thread4 = new Thread(runnable);
thread4.start();
Thread thread5 = new Thread(runnable);
thread5.start(); while (thread1.isAlive() || thread2.isAlive() || thread3.isAlive() || thread4.isAlive() || thread5.isAlive()) {
//自旋
}
long endTime = System.currentTimeMillis();
System.out.println("耗时:"+ (endTime - startTime));
}
}

性能对比说明:https://www.cnblogs.com/flying607/p/5733043.html

最新文章

  1. vsftp匿名用户搭建
  2. Struct2 csv文件上传读取中文内容乱码
  3. DRUPAL-PSA-CORE-2014-005 &amp;&amp; CVE-2014-3704 Drupal 7.31 SQL Injection Vulnerability /includes/database/database.inc Analysis
  4. HTML(Open Method)翻译自MSDN
  5. UISegmetControl
  6. c语言中的结构体为值类型,当把一个结构体赋值给另一个结构体时,为值传递
  7. centos6.5 64位 openvpn安装配置
  8. ubuntu 解压rar
  9. SAP屏幕框架的创建
  10. hdu 4970 Killing Monsters(数学题)
  11. apt-get 总结2
  12. Webdriver+testNG+ReportNG+Maven+SVN+Jenkins自动化测试框架的pom.xml配置
  13. 作为一个新人,怎样学习嵌入式Linux
  14. swift之函数式编程(四)
  15. 洛谷 P1028 数的计算【递推】
  16. 【开发技术】Get请求和Post请求区别
  17. CSS层叠和继承
  18. openssl 生成pfx
  19. python之路--反射
  20. 【转载】一个小时学会MySQL数据库

热门文章

  1. 谁能率先挖掘出5G金矿?
  2. springboot学习笔记:12.解决springboot打成可执行jar在linux上启动慢的问题
  3. Windows电脑忘记密码
  4. mysql查找json格式列的指定字段值
  5. jQ给下拉框绑定事件,为什么要绑定在框(select标签)上,而不是绑定在选项(option标签)上
  6. 83)PHP,配置文件功能
  7. jtemplates使用+同内容列合并
  8. C语言数据类型char
  9. hibernate主键(generator)生成方式
  10. vue日常问题总结