编写3个线程,其中线程threadA打印1-52.线程threadB打印A-Z,线程threadC打印a-z打印顺序要求是12Aa34Bb---5152Zz

本文介绍了使用Java的Lock和Condition实现三个线程交替打印1到52、A到Z以及a到z的案例。通过创建ReentrantLock并定义三个Condition,每个线程在满足特定条件时进行等待和唤醒,确保打印顺序正确。代码中展示了如何使用while循环防止虚假唤醒,并通过sleep方法控制线程启动顺序,以达到预期的打印效果。
摘要由CSDN通过智能技术生成

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

题目:编写3个线程,其中线程threadA打印1-52.线程threadB打印A-Z,线程threadC打印a-z打印顺序要求是12Aa34Bb—5152Zz


一、利用lock、Condition解决问题,实现Runnable接口。

一开始是可以想到用join()解决问题,但是join()执行过后,线程就死了。不能循环打印。

二、运行结果在这里插入图片描述

三、代码

代码如下(示例):

package test;

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

public class T1 implements Runnable{
    String name1;
    String name2;
    String name3;
    private int num = 1;
    private Lock lock = new ReentrantLock();//创建锁对象
    private Condition condition1 = lock.newCondition();//条件1
    private Condition condition2 = lock.newCondition();//条件2
    private Condition condition3 = lock.newCondition();//条件3
    T1(String n1,String n2,String n3){
        this.name1=n1;
        this.name2=n2;
        this.name3=n3;
    }
    @Override
    public void run() {
            if(Thread.currentThread().getName().equals(name1)){
                lock.lock();
                while (num != 1){//这里jdk源码里推荐用while,因为有可能出现虚假唤醒,所以要再次确认
                    try {
                        condition1.await();//条件1线程等待,并释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                num=2;
                for(int i=1;i<=52;i++){
                    System.out.print(i);
                    if(i%2==0){
                        try {
                            condition2.signal();//总是唤醒2;
                            if (i != 52) {//i=52时表示为最后一次,所以不进入等待,以便让进程一死亡,确保程序自动结束,下面类似代码功能类似
                                condition1.await();
                            }

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                lock.unlock();
            }else if(Thread.currentThread().getName().equals(name2)){
                lock.lock();
                while (num != 2){//这里jdk源码里推荐用while,因为有可能出现虚假唤醒,所以要再次确认
                    try {
                        condition2.await();//条件2线程等待,并释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                num=3;
                for(int i=0;i<=25;i++){
                    System.out.print((char)('A'+i));
                    try {
                        condition3.signal();
                        if ((char) ('A' + i) != 'Z') {
                            condition2.await();
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.unlock();
            }else if(Thread.currentThread().getName().equals(name3)){
                lock.lock();
                while (num != 3){//这里jdk源码里推荐用while,因为有可能出现虚假唤醒,所以要再次确认
                    try {
                        condition3.await();//条件3线程等待,并释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                num=1;
                for(int i=0;i<=25;i++){
                    System.out.print((char)('a'+i));
                    try {
                        condition1.signal();
                        if ((char) ('a' + i) != 'z') {
                            condition3.await();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.unlock();
            }
    }
}



**

测试

**

package test;

public class Main {
    public static void main(String[] args){
    T1 t1=new T1("线程一","线程二","线程三");
    Thread thread1=new Thread(t1,"线程一");
        Thread thread2=new Thread(t1,"线程二");
        Thread thread3=new Thread(t1,"线程三");
        thread1.start();
        try {
            thread1.sleep(100);//延时,保证一开始的顺序正确
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.start();
        try {
            thread2.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread3.start();
        try {
            thread3.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用线程的 wait() 和 notify() 方法来实现按顺序打印ABC的需求。具体实现如下: ```java public class PrintABC { private int times; // 打印次数 private int state; // 当前状态:0-A,1-B,2-C public PrintABC(int times) { this.times = times; this.state = 0; } public synchronized void printA() throws InterruptedException { for (int i = 0; i < times; i++) { while (state != 0) { wait(); } System.out.print("A"); state = 1; notifyAll(); } } public synchronized void printB() throws InterruptedException { for (int i = 0; i < times; i++) { while (state != 1) { wait(); } System.out.print("B"); state = 2; notifyAll(); } } public synchronized void printC() throws InterruptedException { for (int i = 0; i < times; i++) { while (state != 2) { wait(); } System.out.print("C"); state = 0; notifyAll(); } } } ``` 在主函数中创建三个线程,分别调用 PrintABC 类中的 printA()、printB() 和 printC() 方法: ```java public static void main(String[] args) { PrintABC printABC = new PrintABC(10); Thread threadA = new Thread(() -> { try { printABC.printA(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread threadB = new Thread(() -> { try { printABC.printB(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread threadC = new Thread(() -> { try { printABC.printC(); } catch (InterruptedException e) { e.printStackTrace(); } }); threadA.start(); threadB.start(); threadC.start(); } ``` 执行结果: ```java ABCABCABCABCABCABCABCABCABCABC ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值