更多内容请关注:

锁清秋
package fuxi.concurrency;
import org.junit.Test;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.System.out;
import static java.lang.Thread.currentThread;
import static java.util.concurrent.TimeUnit.SECONDS;
public class JUC {
private Executor executor = ThreadPool.getThreadPool();
@Test
public void atomic() {
AtomicInteger atomicInteger = new AtomicInteger();
out.println("atomicInteger = " + atomicInteger.incrementAndGet());
}
@Test
public void semaphoreTest() {
Semaphore toilet = new Semaphore(3);
int beauty = 20;
while (beauty-- > 0) {
new Thread(() -> {
try {
toilet.acquire();
out.println(currentThread().getName() + "抢到了坑");
out.println(currentThread().getName() + "正在上厕所。。。。。。。。。。");
try { SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
out.println(currentThread().getName() + "厕所上完了");
toilet.release();
}
}, "美女--" + beauty + " 号").start();
}
while (true)
;
}
@Test
public void countDownLatch() {
CountDownLatch student = new CountDownLatch(10);
int studentsNumber = 10;
while (studentsNumber-- > 0) {
new Thread(() -> {
out.println(currentThread().getName() + " 关门离开了!");
student.countDown();
}, studentsNumber + "号学生").start();
}
new Thread(() -> {
try {
student.await();
out.println(currentThread().getName() + "锁门离开!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "monitor").start();
while (true)
;
}
@Test
public void cyclicBarrier() {
CyclicBarrier bankKey = new CyclicBarrier(5);
int numberOfManagers = 5;
while (numberOfManagers-- > 0) {
new Thread(() -> {
out.println(currentThread().getName() + "正在赶来的路上。。。");
try { TimeUnit.SECONDS.sleep(((int) (Math.random() * 10)) % 3); } catch (InterruptedException e) {
e.printStackTrace();
}
out.println(currentThread().getName() + "到了!");
try {
bankKey.await();
out.println(currentThread().getName() + "开完保险柜后去干其他事了!");
} catch (Exception e) {
e.printStackTrace();
}
}, numberOfManagers + "号经理").start();
}
while (true) {
}
}
}