public class SemphoreCountThread extends Thread{
private Semaphore mSemaphore;
private String mThreadName;
public SemphoreCountThread(Semaphore semaphore, String name){
this.mSemaphore = semaphore;
this.mThreadName = name;
this.start();
}
@Override
public void run() {
if(mSemaphore != null){
try {
mSemaphore.acquire();
System.out.println(mThreadName + " is getAcquired");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i = 0;i < 5;i++){
System.out.println(mThreadName+"is count"+ i);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(mSemaphore != null) {
mSemaphore.release();
}
}
public static void main(String[] args){
Semaphore semaphore = new Semaphore(1);
SemphoreCountThread countThread01 = new SemphoreCountThread(semaphore,"countThread01");
SemphoreCountThread countThread02 = new SemphoreCountThread(semaphore,"countThread02");
}
}
public class CyclicBarrierThread extends Thread{
private CyclicBarrier mCyclierBarrier;
private String mName;
public CyclicBarrierThread(CyclicBarrier cyclicBarrier, String name){
this.mCyclierBarrier = cyclicBarrier;
this.mName = name;
this.start();
}
@Override
public void run() {
System.out.println("---"+mName);
try {
mCyclierBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
CyclicBarrier mCyclicBarrier = new CyclicBarrier(3, new Runnable() {
public void run() {
System.out.println("====end");
}
});
new CyclicBarrierThread(mCyclicBarrier,"a");
new CyclicBarrierThread(mCyclicBarrier,"b");
new CyclicBarrierThread(mCyclicBarrier,"c");
}
}