java多线程笔记–lock多线程计数
文章目录
java多线程笔记--lock多线程计数1.lock多线程计数
lock:主要有可重入锁,读写锁,文件锁
1.lock多线程计数
package com.ctg.test.lock;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Description: Lock解决多线程访问相同的资源
* lock的特性:
* 1)相比于 synchronized隐式获取、释放锁,lock需要显示的获取释放锁
* 2)相比于 synchronized,lock可以可中断的获取锁及超时获取锁,
* 3)ReentrantLock,同一个线程调用lock方法,可以连续多次获取锁而不被阻塞
* @Author:
* @Date: 2019/5/12 0:05
*/
public class TestLockCount {
private static int num =0;
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args)throws InterruptedException {
for(int k=0;k<100;k++){
CountDownLatch countDownLatch = new CountDownLatch(3);
num=0;
Thread t1 =new Thread(new CountRunnable(countDownLatch));
Thread t2 =new Thread(new CountRunnable(countDownLatch));
Thread t3 =new Thread(new CountRunnable(countDownLatch));
t1.start();
t2.start();
t3.start();
countDownLatch.await();
System.out.println("第"+(k+1)+"次计算结果,num=" + num);
}
}
public static class CountRunnable implements Runnable{
private CountDownLatch countDownLatch;
CountRunnable (CountDownLatch countDownLatch){
this.countDownLatch=countDownLatch;
}
@Override
public void run() {
lock.lock();
try{
for (int i=0;i<10000;i++){
num=num+1;
// System.out.println(Thread.currentThread().getName()+":"+num);
}
}
finally {
lock.unlock();
}
countDownLatch.countDown();
}
}
}
执行100次结果: