synchronied (actualización de bloqueo)
volitile
AtomicXXXX LongAdder
JUC diversos bloqueo de sincronización
ReentrantLock (CAS)
CountDownLatch
CyclicBarrier
Phaser
ReadWriteLock StampedLock
Semáforo
Intercambiador
LockSupport
Dos hilos 1A2B3C de salida ...
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();
}
productor al Consumidor
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;
}
Defecto es que, notifyAll despertará todos, independientemente de los productores y consumidores
Condición
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> el AQS
2, y co-operación de estado del estado de una lista doblemente enlazada.
. 3, CAS + volitile estado
. 4, estado volitile se modifica, y se proporciona además de la setstate el método de estado () y compareAndState ();
5, el AQS métodos principales:. TryAcquire, tryRelease, tryAcquireShared, tryReleaseShared , isHeldExclusively