算法:三线程打印

Posted danfengw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法:三线程打印相关的知识,希望对你有一定的参考价值。

1 condation方式如下,其他方式参考

https://danfeng.blog.csdn.net/article/details/112133256

public class ThreeThreadPrintCondition 


    public static void main(String[] args) 
        ReentrantLock lock = new ReentrantLock();
        Condition conditionA = lock.newCondition();
        Condition conditionB = lock.newCondition();
        Condition conditionC = lock.newCondition();
        Thread thread1 = new Thread(new Runnable1("A", conditionA, conditionB, lock));
        Thread thread2 = new Thread(new Runnable1("B", conditionB, conditionC, lock));
        Thread thread3 = new Thread(new Runnable1("C", conditionC, conditionA, lock));
        thread1.start();
        thread2.start();
        thread3.start();
    


class Runnable1 implements Runnable 
    private String printStr = "";
    private Condition conditionWait;
    private Condition conditionSignal;
    ReentrantLock lock;
    private int count;

    public Runnable1(String printStr, Condition conditionWait, Condition conditionSignal, ReentrantLock lock) 
        this.printStr = printStr;
        this.conditionWait = conditionWait;
        this.conditionSignal = conditionSignal;
        this.lock = lock;
    

    @Override
    public void run() 
        while (true) 
            lock.lock();
            if (count == 3 * 10 - 1) 
                lock.unlock();
                return;
            
            System.out.println("输出" + printStr);
            ++count;
            conditionSignal.signalAll();
            try 
                conditionWait.await();
             catch (InterruptedException e) 
                e.printStackTrace();
            
            lock.unlock();
        
    

    public boolean needReturn() 

        return count == 3 * 10 - 1;
    

以上是关于算法:三线程打印的主要内容,如果未能解决你的问题,请参考以下文章

顺序打印ABC算法题

顺序打印ABC算法题

多线程-线程一打印1,2,3,4,5线程二打印6,7,8,9,10,线程三打印11,12,13,14,15,...直到45结束

多线程面试题之三线程按顺序交替打印ABC的方法

三线程连续打印ABC

java多线程多线程的创建三种方式--笔记