java多线程笔记--lock多线程计数

Posted SingleOneMan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程笔记--lock多线程计数相关的知识,希望对你有一定的参考价值。

java多线程笔记–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次结果:

以上是关于java多线程笔记--lock多线程计数的主要内容,如果未能解决你的问题,请参考以下文章

Java学习笔记—多线程(java.util.concurrent.locks包,转载)

Java笔记(24):多线程(02)

java多线程笔记--Atomic原子操作类

Java多线程学习笔记— “隐式同步锁(synchronized)与显式同步锁(lock)”

java多线程笔记--生产者消费组模型

python笔记10-多线程之线程同步(锁lock)