二:线程锁 synchronized和lock

同一把锁(synchronized)锁住的代码一次性只能进一个,就像火车上上厕所,一个进去了,后面要进这个厕所的就需要等待他出来为止,但是如果他是进的别的厕所就不相干了

 1)获取锁的线程执行完了改代码块,然后线程释放对锁的占有;

 2)线程执行发生异常,此时JVM会让线程自动释放

具体请看下面:

  https://www.cnblogs.com/weibanggang/p/9470718.html

 

lock锁(不会自动解锁,一定要手动解锁,所以要和try一起用)

1.Lock.lock是加锁,如果拿不到就等待:记得和try finally一起用

2.Lock.trylock 尝试是否拿的到,拿的到就是true拿不到就是false

3.Lock.lockInterruptibly() 去拿锁,拿不到就等待,可以被中断(是thread.interrupt()这里要注意)

4.读写锁。读锁的时候其他可以读,写锁的时候其他不能读也不能写

#代码

  

package TestLockStudy;

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

public  class  interruptibly {
    private  Lock lock =  new  ReentrantLock();   
    public  static  void  main(String[] args)  {
        interruptibly test =  new  interruptibly();
        MyThread thread1 =  new  MyThread(test);
        MyThread thread2 =  new  MyThread(test);
        thread1.start();
        thread2.start();
        
        try  {
            Thread.sleep( 2000 );
        }  catch  (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.interrupt();
    }  
    
    public  void  insert(Thread thread)  throws  InterruptedException{
        lock.lockInterruptibly();    //注意,如果需要正确中断等待锁的线程,必须将获取锁放在外面,然后将InterruptedException抛出
        try  {  
            System.out.println(thread.getName()+ "得到了锁" );
            long  startTime = System.currentTimeMillis();
            for (    ;     ;) {
                if (System.currentTimeMillis() - startTime >= Integer.MAX_VALUE)
                    break ;
                //插入数据
            }
        }
        finally  {
            System.out.println(Thread.currentThread().getName()+ "执行finally" );
            lock.unlock();
            System.out.println(thread.getName()+ "释放了锁" );
        }  
    }
}

class  MyThread  extends  Thread {
    private  interruptibly test =  null ;
    public  MyThread(interruptibly test) {
        this .test = test;
    }
    @Override
    public  void  run() {
        
        try  {
            test.insert(Thread.currentThread());
           
        }  catch  (InterruptedException e) {
            System.out.println(Thread.currentThread().getName()+ "被中断" );
        }
    }
}
lock中断代码

详细看:

  https://blog.csdn.net/drdongshiye/article/details/85269808

posted @ 2020-12-02 19:28  晴晴小可爱的小弟  阅读(82)  评论(0编辑  收藏  举报