feiniao2029 发表于 2013-2-1 11:22:24

控制线程顺序,使用semaphore信号量机制

有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC…


package pcenshao.thread;

import java.util.concurrent.Semaphore;

public class SemaphoreABC {
   
    static class T extends Thread{
      
      Semaphore me;
      Semaphore next;
      
      public T(String name,Semaphore me,Semaphore next){
            super(name);
            this.me = me;
            this.next = next;
      }
      
      @Override
      public void run(){
            for(int i = 0 ; i < 10 ; i ++){
                try {
                  me.acquire();
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
                System.out.println(this.getName());
                next.release();
            }
      }
    }
   
    public static void main(String[] args) {
      Semaphore aSem = new Semaphore(1);
      Semaphore bSem = new Semaphore(0);
      Semaphore cSem = new Semaphore(0);
      
      T a = new T("A",aSem,bSem);
      T b = new T("B",bSem,cSem);
      T c = new T("C",cSem,aSem);
      
      a.start();
      b.start();
      c.start();
    }
}
页: [1]
查看完整版本: 控制线程顺序,使用semaphore信号量机制