多线程与高并发4-线程之间通讯

synchronied(锁升级)
volitile
AtomicXXXX LongAdder

JUC各种同步锁

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

两个线程输出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();
    }

生产者消费者

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;
	}

瑕疵在于,notifyAll会叫醒所有,不论生产者和消费者

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->AQS
2、state和共同操作该state的双向链表。
3、CAS+Volitile state
4、state是volitile修饰的,并且设置state方法除了有setState()和compareAndState();
5、AQS主要方法:tryAcquire,tryRelease,tryAcquireShared,tryReleaseShared,isHeldExclusively

发布了25 篇原创文章 · 获赞 0 · 访问量 583

猜你喜欢

转载自blog.csdn.net/RaymondCoder/article/details/105081052