多線程與併發 原理

synchronized

synchronized 底層實現原理

package com.interview.javabasic.thread;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo implements Runnable{
    private static ReentrantLock lock = new ReentrantLock(false);// 這裏 false 就是非公平 true就是公平
    @Override
    public void run(){
        while (true){
            try{
                lock.lock();
                System.out.println(Thread.currentThread().getName() + " get lock");
                Thread.sleep(1000);
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo rtld = new ReentrantLockDemo();
        Thread thread1 = new Thread(rtld);
        Thread thread2 = new Thread(rtld);
        thread1.start();
        thread2.start();
    }
}

複製代碼

unsafe 不安全的後門方法

CAS Compare and Swap

java 線程池

相關文章
相關標籤/搜索