那些网站做的非常好看的,中国城乡建中国城乡建设部网站,wordpress首页视频自动播放,事业单位报名网站可重⼊锁#xff0c;这个锁可以被线程多次重复进⼊进⾏获取操作。 ReentantLock继承接⼝Lock并实现了接⼝中定义的⽅法#xff0c;除了能完成synchronized所能完成的所有⼯作 外#xff0c;还提供了诸如可响应中断锁、可轮询锁请求、定时锁等避免多线程死锁的⽅法。 在并发量…可重⼊锁这个锁可以被线程多次重复进⼊进⾏获取操作。 ReentantLock继承接⼝Lock并实现了接⼝中定义的⽅法除了能完成synchronized所能完成的所有⼯作 外还提供了诸如可响应中断锁、可轮询锁请求、定时锁等避免多线程死锁的⽅法。 在并发量较⼩的多线程应⽤程序中ReentrantLock与synchronized性能相差⽆⼏但在⾼ 并发量的条件下synchronized性能会迅速下降⼏⼗倍⽽ReentrantLock的性能却能依然维持⼀个⽔ 准。 因此我们建议在⾼并发量情况下使⽤ReentrantLock。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class Counter {private final Lock lock new ReentrantLock();private int count 0;public void increment() {lock.lock(); // 获取锁try {count;} finally {lock.unlock(); // 释放锁}}public int getCount() {return count;}public static void main(String[] args) {Counter counter new Counter();// 创建两个线程模拟并发访问共享资源Thread t1 new Thread(() - {for (int i 0; i 1000; i) {counter.increment();}});Thread t2 new Thread(() - {for (int i 0; i 1000; i) {counter.increment();}});t1.start();t2.start();// 等待两个线程执行完毕try {t1.join();t2.join();} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Final count is: counter.getCount());}
}public class Counter {private int count 0;// 使用 synchronized 关键字修饰方法确保线程安全public synchronized void increment() {count;}public int getCount() {return count;}public static void main(String[] args) {Counter counter new Counter();Thread t1 new Thread(() - {for (int i 0; i 1000; i) {counter.increment();}});Thread t2 new Thread(() - {for (int i 0; i 1000; i) {counter.increment();}});t1.start();t2.start();try {t1.join();t2.join();} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Final count is: counter.getCount());}
}