Multi-threaded communication between threads and high concurrent 4-

synchronied (lock upgrade)
volitile
AtomicXXXX LongAdder

JUC various synchronization lock

ReentrantLock(CAS)
CountDownLatch
CyclicBarrier
Phaser
ReadWriteLock StampedLock
Semaphore
Exchanger
LockSupport

Two threads output 1A2B3C ...

static String[] words = {"A","B","C","D"};
    static String[] num = {"1","2","3","4"};
    static Thread t1=null;
    static Thread t2=null;
    public static void main(String[] args) {
        t1 = new Thread(() ->{
           for (int i=0;i<3;i++){
               System.out.println(words[i]);
               LockSupport.park();
               LockSupport.unpark(t2);
           }
        });

        t2 = new Thread(() ->{
            for (int i=0;i<3;i++){
                System.out.println(num[i]);
                LockSupport.unpark(t1);
                LockSupport.park();
            }
        });

        t1.start();
        t2.start();
    }

Producer Consumer

public synchronized void put(T t) {
 		//达到生产最大值10,await()
		while(lists.size() == MAX) {//while避免其他线程进来,仍然判断MAX
			try {
				this.wait(); //effective java
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		lists.add(t);
		++count;
		this.notifyAll(); //通知消费者线程进行消费
	}
	
	public synchronized T get() {
		T t = null;
		while(lists.size() == 0) {//
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		t = lists.removeFirst();
		count --;
		this.notifyAll(); //通知生产者进行生产
		return t;
	}

Flaw is that, notifyAll will wake all, regardless of producers and consumers

Condition

    private Lock lock = new ReentrantLock();
	private Condition producer = lock.newCondition();
	private Condition consumer = lock.newCondition();
	
	public void put(T t) {
		try {
			lock.lock();
			while(lists.size() == MAX) {
				producer.await();
			}
			
			lists.add(t);
			++count;
			consumer.signalAll(); //通知消费者线程进行消费
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	
	public T get() {
		T t = null;
		try {
			lock.lock();
			while(lists.size() == 0) {
				consumer.await();
			}
			t = lists.removeFirst();
			count --;
			producer.signalAll(); //通知生产者进行生产
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return t;
	}
	

AQS (CLH)

. 1, nonfairsync-> sync-> the AQS
2, and co-operation state of the state of a doubly linked list.
. 3, CAS + Volitile state
. 4, volitile state is modified, and is provided in addition to the setState the state method () and compareAndState ();
. 5, the AQS main methods: tryAcquire, tryRelease, tryAcquireShared, tryReleaseShared , isHeldExclusively

Published 25 original articles · won praise 0 · Views 583

Guess you like

Origin blog.csdn.net/RaymondCoder/article/details/105081052