六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 52|回复: 0

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

[复制链接]

升级  6%

13

主题

13

主题

13

主题

秀才

Rank: 2

积分
59
 楼主| 发表于 2013-1-26 14:02:33 | 显示全部楼层 |阅读模式
有三个线程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();
    }
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表