JUC并发编程(Concurrent)
java.util.concurrent
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i=0;i<6;i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"同学离开教室");
countDownLatch.countDown();
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+"班长关门");
}
CyclicBarrier cb = new CyclicBarrier(7,()->{
System.out.println("召唤神龙");
});
for (int i=1;i<=7;i++){
final int temp = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"搜集到第"+temp+"颗龙珠");
try {
cb.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
Semaphore s = new Semaphore(3);
for (int i=1;i<=6;i++){
new Thread(()->{
try {
s.acquire();
System.out.println(Thread.currentThread().getName()+"抢到了车位");
try{
TimeUnit.SECONDS.sleep(4);
System.out.println(Thread.currentThread().getName()+"离开了车位");
}catch (InterruptedException e){
e.printStackTrace();
}finally {
s.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},String.valueOf(i));
}
java.util.concurrent.locks
class MyCache{
private volatile Map<String,Object> map = new HashMap<>();
private ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
public void put(String key,Object value){
readWriteLock.writeLock().lock();
try{
System.out.println(Thread.currentThread().getName()+"开始写入");
try {
TimeUnit.MICROSECONDS.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
map.put(key,value);
System.out.println(Thread.currentThread().getName()+"写入完成");
}catch(Exception e){
e.printStackTrace();
}finally {
readWriteLock.writeLock().unlock();
}
}
public void get(String key){
readWriteLock.readLock().lock();
try{
System.out.println(Thread.currentThread().getName()+"读取数据");
try {
TimeUnit.MICROSECONDS.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+"读取完成"+o);
}catch(Exception e){
e.printStackTrace();
}finally {
readWriteLock.readLock().unlock();
}
}
}
public class TestConcurrent {
public static void main(String[] args) {
MyCache m = new MyCache();
for (int i = 1; i <= 7; i++) {
final int temp = i;
new Thread(() -> {
m.put(temp+"",temp+"");
}, String.valueOf(i)).start();
}
for (int i = 1; i <= 7; i++) {
final int temp = i;
new Thread(() -> {
m.get(temp+"");
}, String.valueOf(i)).start();
}
}
}
java.collections.Queue.BlockingQueue(阻塞队列)
BlockingQueue<String> b = new ArrayBlockingQueue(3);
b.offer("a",3L, TimeUnit.SECONDS);
b.poll(3L, TimeUnit.SECONDS);