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

java多线程轮流打印数字字母案例代码

时间:2020-02-21 17:46:55      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:start   system   ttl   code   lock   cat   nal   rgs   cep   

本案例演示3个线程轮流打印输出数字字母;代码如下

package thread;

public class ThreadTest {
    public static void main(String[] args) {
        Print print = new Print();
        new Thread(()->{
            print.printNum();
        }).start();

        new Thread(()->{
            print.printZimu();
        }).start();

        new Thread(()->{
            print.printZimuLittle();
        }).start();
    }
}
package thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Print {
    final Lock lock = new ReentrantLock();
    final Condition num = lock.newCondition();
    final Condition zimu = lock.newCondition();
    final Condition zimuLittle = lock.newCondition();

    public void printNum(){
        lock.lock();
        try {
            for (int i=1;i<53;i++){
                System.out.print(i);
                if (i%2==0){
                    zimu.signal();
                    num.await();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printZimu(){
        lock.lock();
        try {
            for (int i=0;i<26;i++){
                System.out.print((char)(i+‘A‘));
                zimuLittle.signal();
                zimu.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printZimuLittle(){
        lock.lock();
        try {
            for (int i=0;i<26;i++){
                System.out.print((char)(i+‘a‘));
                num.signal();
                zimuLittle.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

最终输出结果为12aA34bB56cC78dD910eE1112fF1314gG1516hH1718iI1920jJ2122kK2324lL2526mM2728nN2930oO3132pP3334qQ3536rR3738sS3940tT4142uU4344vV4546wW4748xX4950yY5152zZ

java多线程轮流打印数字字母案例代码

标签:start   system   ttl   code   lock   cat   nal   rgs   cep   

原文地址:https://blog.51cto.com/14700157/2472675

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