码迷,mamicode.com
首页 > 编程语言 > 详细

线程轮流顺序交替执行

时间:2018-11-04 21:10:56      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:max   i++   factory   执行   测试   this   lock   exception   tor   

公司一道考试题:启动三个线程打印递增的数字,
线程1先打印1,2,3,4,5,然后是线程2打印6,7,8,9,10,然后是线程3打印11,12,13,14,15,
接着再由线程1打印16,17,18,19,20...由此类推,直到打印到75

打印线程对象:

public class Printer extends Thread{
 
    private static final Logger LOG = LoggerFactory.getLogger(Printer.class);
 
    private static final int INDEX_MAX = 75;
    
    private static int index = 0;
    
    private int count;
    
    private Lock lock;
 
    private Condition condition;
    
    private Condition nextCondition;
 
    public Printer(String name,Lock lock,Condition condition,Condition nextCondition,int count){
        this.setName(name);
        this.count = count;
        this.lock = lock;
        this.condition = condition;
        this.nextCondition = nextCondition;
    }
 
    @Override
    public void run(){
        while(true){
            lock.lock();
            try{
                condition.await();
                if(index >= INDEX_MAX){
                    LOG.info("已达到最大值,停止计数"); 
                    nextCondition.signal();//停止自己之前将下一个线程唤醒
                    return;
                }
                
                for(int i = 0;i < count;i++){
                    LOG.info(String.valueOf(++index));
                }
                nextCondition.signal();
            } catch (InterruptedException e) {
                //忽略
            }finally{
                lock.unlock();
            }
        }
    }
 
}

测试类:

public class BootStrap { 
    
    public static void main(String[] args) throws InterruptedException {
        Lock lock = new ReentrantLock();
        Condition condition_1 = lock.newCondition();
        Condition condition_2 = lock.newCondition();
        Condition condition_3 = lock.newCondition();
        
        Printer printer1 = new Printer("Print-Thread-1",lock,condition_1,condition_2,5);
        Printer printer2 = new Printer("Print-Thread-2",lock,condition_2,condition_3,5);
        Printer printer3 = new Printer("Print-Thread-3",lock,condition_3,condition_1,5);
        
        printer1.start();
        printer2.start();
        printer3.start();
        
        Thread.sleep(10);//这里主线程睡一会,等待printer到达阻塞点,如果提前唤醒,printer将会永远阻塞下去
        
        //放开第一个
        lock.lock();
        try{
            condition_1.signal();
        } finally{
            lock.unlock();
        }
    }
}

 

线程轮流顺序交替执行

标签:max   i++   factory   执行   测试   this   lock   exception   tor   

原文地址:https://www.cnblogs.com/shanhm1991/p/9905298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!