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