ReentrantLock 线程安全锁的机制

放肆的年华 提交于 2019-12-25 06:56:37

1 具有线程锁的安全机制
2 可以在各个线程抢占时,线程之间切换更加频繁
代码如下

package com.exception2;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class Ex4 implements  Runnable  {
    private int taks=100;
    private ReentrantLock lk=new ReentrantLock(true);
    @Override
    public void run() {
        while (true){
            try{
                lk.lock();
                if(taks>0){
                    try {
                        Thread.sleep(40);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+":"+taks--);
                }else {
                    break;
                }
            }finally {
                lk.unlock();
            }

        }
    }
}
public class Main4 {
    public static void main(String[] args) {
          Ex4 e=new Ex4();
        new Thread(e).start();
        new Thread(e).start();
        new Thread(e).start();
        new Thread(e).start();
        new Thread(e).start();
        new Thread(e).start();
        new Thread(e).start();
        new Thread(e).start();
        new Thread(e).start();
        new Thread(e).start();
        new Thread(e).start();
        new Thread(e).start();

    }
}

private ReentrantLock lk=new ReentrantLock(true);
锁机制为true时 运行效果
在这里插入图片描述
private ReentrantLock lk=new ReentrantLock(false);//不写参数时候,默认也为false
锁机制为false时 运行效果
在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!