先说一下常用的线程同步锁synchronized、ReentrantLock、Semaphore、AtomicInteger
1、synchronized(同步锁)
给共享资源上锁,只有拿到锁的线程才能访问共享资源
2、ReentrantLock(可重入锁、公平锁、非公平锁)
公平锁:先来的线程会优先获取到锁(线程等待时间长的会先获取到锁)。
非公平锁:随机取一个线程获取锁。
相比synchronized来说,上锁和解锁需要手动实现,而且在高并发情况下,这个相对synchronized更好。
「代码实现」
public class ReentrantLockTest{
    
    # true公平锁 false非公平锁
    private static final Lock lock = new ReentrantLock(true);
    public static void main(String[] args){
        new Thread(() -> test(),"线程1").start();
        new Thread(() -> test(),"线程2").start();
        new Thread(() -> test(),"线程3").start();
        new Thread(() -> test(),"线程4").start();
        new Thread(() -> test(),"线程5").start();
    }
    public static void test(){
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"获取了锁");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName()+"释放了锁");
            lock.unlock();
        }
    }
}
公平锁执行结果 非公平锁执行结果


今天先写到这儿吧,累了,剩下明天再写
                  
                  
                  
                  
                            
本文详细介绍了Java中常用的线程同步机制,包括synchronized、ReentrantLock等,并通过示例代码展示了如何使用ReentrantLock实现公平锁和非公平锁。
          
      
          
                
                
                
                
              
                
                
                
                
                
              
                
                
              
            
                  
					612
					
被折叠的  条评论
		 为什么被折叠?
		 
		 
		
    
  
    
  
            


            