下面的代码,不加mys.acquire();和mys.release();的时候,各线程会交替输出。
加上的话,各线程会串行输出,说明信号量机制生效了。
MySemaphore.java
加上的话,各线程会串行输出,说明信号量机制生效了。
MySemaphore.java
interface Semaphore {
void acquire();
void release();
}
public class MySemaphore implements Semaphore{
private StringBuffer runFlag = new StringBuffer("true");
public void acquire(){
synchronized(runFlag){
if(runFlag.toString().equals("true")){
runFlag.setLength(0);
runFlag.append("false");
}else{
try{
runFlag.wait();
runFlag.setLength(0);
runFlag.append("false");
}catch(Exception e){
e.printStackTrace();
}
}
}
}
public void release(){
synchronized(runFlag){
runFlag.setLength(0);
runFlag.append("true");
try{
runFlag.notify();
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args){
Runnable run = new Runnable(){
MySemaphore mys = new MySemaphore();
public void run(){
mys.acquire();
System.out.println(Thread.currentThread().getName() + " start");
for(int j=0;j<10;j++){
System.out.println(Thread.currentThread().getName() + " start " + j);
}
System.out.println(Thread.currentThread().getName() + " end");
mys.release();
}
};
Thread t;
for(int i=0;i<10;i++){
t = new Thread(run);
t.start();
}
}
}