Thread线程安全二

什么是线程安全?

多个线程操纵变量,能保持变量的一致性,正确性,没有发生相互修改和串行的情况。

隐式锁,又称为线程同步synchronized

syschronized可以对一个方法使用,也可以对一个代码快进行使用。

    public synchronized void Set(){

    }
    public void set(){
        synchronized(this){
            
        }
    }

多个线程访问是遵循FIFO先来先用。

syschronized不用手动创建锁和释放锁。

显示锁Lock和ReentrantLock。

无条件的,可轮询的,定时的,可中断的。所有加锁和释放都是显示的。

ReentrantLock是Lock的实现类

只要对所需要加锁的地方加锁即可,可以在类中加锁也可以在类外加锁

package gavin;

public class ReentrantLockTest{

    public void start(){
        System.out.println(Thread.currentThread().getName()+" start");
    }
    public void state(){
        System.out.println( Thread.currentThread().getName()+" "+Thread.currentThread().getState());
    }
}
public class Main {

    private static final ReentrantLock reentrantLock = new ReentrantLock();
    public static void main(String[] args) throws Exception{
         ReentrantLockTest test = new ReentrantLockTest();

        for (int i = 0; i < 3; i++) {
            new Thread(){
                public void run (){
                    reentrantLock.lock();
                    test.start();
                    reentrantLock.unlock();
                }
            }.start();
        }
        for (int i = 0; i < 3; i++) {
            new Thread(){
                public void run(){
                    reentrantLock.lock();
                    test.state();
                    reentrantLock.unlock();

                }
            }.start();
        }
    }


}

 

import java.util.concurrent.locks.ReentrantReadWriteLock;

class Count{
        private  final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
        public void get(){
            rwl.readLock().lock();
            try{
                System.out.println(Thread.currentThread().getName()+" start");
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName()+" end");
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            finally{
                rwl.readLock().unlock();
            }
            
        }
        public void set(){
            rwl.writeLock().lock();
            try{
                System.out.println(Thread.currentThread().getName()+" write Thread start");
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName()+" write Thread end");
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            finally{
                rwl.writeLock().unlock();
            }
        }
    }

读写锁,读读不互斥,读写互斥,写写互斥。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值