import java.util.concurrent.CountDownLatch;
public class MyCountDownlatch {
public static void main(String[] args) throws InterruptedException {
CountDownLatch c = new CountDownLatch(2);
Thread t1 = new MyThread(c);
Thread t2 = new MyThread(c);
t1.start();
t2.start();
c.await();
System.out.println("主线程执行完毕");
}
}
class MyThread extends Thread{
private CountDownLatch c;
public MyThread(CountDownLatch c){
this.c = c;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName());
System.out.println("count:"+c.getCount());
c.countDown();
System.out.println("count:"+c.getCount());
}
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class MyCyclicBarrier {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(4);
new Writer(barrier).start();
new Writer(barrier).start();
new Writer(barrier).start();
new Writer(barrier).start();
}
}
class Writer extends Thread{
private CyclicBarrier barrier;
public Writer(CyclicBarrier barrier){
this.barrier = barrier;
}
@Override
public void run() {
System.out.println(getName()+"开始执行。");
try {
sleep(1000);
} catch (InterruptedException e) {
}
try {
System.out.println("等待的线程数:"+barrier.getNumberWaiting());
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
}
System.out.println(getName()+"结束执行。");
}
}
import java.util.concurrent.Semaphore;
public class MySemaphore {
public static void main(String[] args) {
Semaphore wc = new Semaphore(3);
for(int i = 0;i<10;i++){
new WcThread(wc,"第"+i+"个人").start();;
}
}
}
class WcThread extends Thread{
private String name;
private Semaphore wc;
public WcThread(Semaphore wc,String name){
this.wc = wc;
this.name = name;
}
@Override
public void run() {
int availablePermits = wc.availablePermits();
if(availablePermits >0 ){
System.out.println(name+",有可用茅坑。");
}else{
System.out.println(name+",没有坑。");
}
try {
wc.acquire();
System.out.println(name+",进入茅坑。");
Thread.sleep(1000);
System.out.println(name+",上完了,释放茅坑。");
wc.release();
} catch (InterruptedException e) {
}
}
}