首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

控制线程顺序,使用se地图hore信号量机制

2012-12-24 
控制线程顺序,使用semaphore信号量机制有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次AB

控制线程顺序,使用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();
    }
}

热点排行