synchronied(ロックアップ)
volitile
AtomicXXXX LongAdder
JUCさまざまな同期ロック
ReentrantLockの(CAS)
たCountDownLatch
CyclicBarrierを
フェイザー
ReadWriteLock StampedLock
セマフォ
交換
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は関係なく、生産者と消費者の、すべてを覚ますだろう、ということです
調子
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、および共運転状態。
。3、CAS + Volitile状態
。4、volitile状態が変更され、状態法をSETSTATEに加えて提供され、()及びcompareAndState();
5、AQSメイン方法:。tryAcquire、tryRelease、tryAcquireShared、tryReleaseShared 、isHeldExclusively