线程轮流顺序交替执行

Posted shanhm1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程轮流顺序交替执行相关的知识,希望对你有一定的参考价值。

公司一道考试题:启动三个线程打印递增的数字,
线程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();
        }
    }
}

 

以上是关于线程轮流顺序交替执行的主要内容,如果未能解决你的问题,请参考以下文章

多线程基础

Java多线程编程基础知识汇总

进程与线程-基本概念

进程线程和协程

多线程基础

java线程执行完后自己结束吗