线程池(ThreadPoolExecutor)的七个参数

2024-01-09 14:47:26 浏览数 (3)

Java实现线程安全的三种方式

1.同步代码块

代码语言:javascript复制
public class test{
    
    static int tickets = 15;
    
    class SellTickets implements Runnable{
        @Override
        public void run(){
            while (tickets > 0){
                //同步代码块
                synchronized(this){
                    if(tickets <= 0){
                        return;
                    }
                }
            }
        }
    }
}

2.同步方法

代码语言:javascript复制
public class ThreadSynchroniazedMethodSecurity{
    static int tickets = 15;
    class SellTickets implements Runnable{
        @Override
        public void run(){
            while(tickets > 0){
                synMethod();
            }
        }
        
        synchronized void synMethod(){
            synchronized(this){
                ....
            }
        }
    }
    
}

3.Lock锁机制

Lock锁机制,通过创建Lock对象,采用lock()枷锁,unlock()解锁,来保护指定的代码块

代码语言:javascript复制
public class ThreadLockSecurity{
    static int tickets = 15;
    
    class SellTickets implements Runnable{
        Lock lock = new ReentrantLock();
        @Override
        public void run(){
            while(tickets > 0){
                try{
                    lock lock();
                    ...
                }catch(Exception e){
                    
                }finally{
                    lock.unlock();
                    ...
                }
            }
        }
    }
}

0 人点赞