三线程交替打印指定字符串

本文介绍了一个使用Java实现的多线程交替打印字符串的方法,通过synchronized关键字和wait、notifyAll方法控制线程间的同步,确保了字符的正确交替输出。同时,展示了如何使用Runnable接口创建线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class a200602经典多线程 {
    static int num = 0;
    //给定一个字符串双线程交替打印
    static class MyThread extends Thread{
        private  String str;
        private  String str2;
        public MyThread(String str,String str2) {
            this.str = str;
            this.str2 = str2;
        }
        @Override
        public void  run() {
            synchronized (MyThread.class){
              for(;num<str.length();){ 
                 System.out.println(str.charAt(num)+str2); 
                 num++;     
                  MyThread.class.notifyAll();
                  try{
                      MyThread.sleep(100);
                      MyThread.class.wait();
                  }catch (Exception E){
                      E.printStackTrace();
                  }
              }
            }
        }
    }


    public static void main(String[] args) {
        String str = "213456789";
        MyThread t1 = new MyThread(str,"第一个线程");
        MyThread t2 = new MyThread(str,"第二个线程");
        MyThread t3 = new MyThread(str,"第三个线程");
        t1.start();
        t2.start();
        t3.start();
    }
}

若是双线程交替打印,则将run方法中的notifyAll替换成notify。对于特殊的字符串也可以通过写多个thread分别实现。

//======================runable

static class Thread3 implements Runnable{
       private   String str;

        public Thread3(String str) {
            this.str = str;
        }



          public void run() {
           for(char a : str.toCharArray()){
               System.out.print(a);
           }

        }
  }


public static void main(){
     Thread3 ts = new Thread3("str");
     new Thread(ts).start();
     new Thread(ts).start();
     new Thread(ts).start();
}
利用线程池实现三个线程交替打印的功能,可以借助 `java.util.concurrent` 包下的工具类完成。下面是一个示例代码,展示了如何通过信号量机制让三个线程按顺序交替打印数字。 ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class AlternatePrint { private static final int TOTAL_TASK = 30; // 总任务数 public static void main(String[] args) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(3); Semaphore semaphoreA = new Semaphore(1); // A先执行 Semaphore semaphoreB = new Semaphore(0); Semaphore semaphoreC = new Semaphore(0); Runnable taskA = () -> { for (int i = 0; i < TOTAL_TASK / 3; i++) { try { semaphoreA.acquire(); System.out.println("Thread A prints " + (i * 3 + 1)); semaphoreB.release(); // 唤醒B } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; Runnable taskB = () -> { for (int i = 0; i < TOTAL_TASK / 3; i++) { try { semaphoreB.acquire(); System.out.println("Thread B prints " + (i * 3 + 2)); semaphoreC.release(); // 唤醒C } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; Runnable taskC = () -> { for (int i = 0; i < TOTAL_TASK / 3; i++) { try { semaphoreC.acquire(); System.out.println("Thread C prints " + (i * 3 + 3)); semaphoreA.release(); // 回到唤醒A } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; executor.submit(taskA); executor.submit(taskB); executor.submit(taskC); executor.shutdown(); } } ``` 该序实现了三个线程按照指定次序依次打印的任务。每一个任务在打印完成后会释放下一个任务的锁,如此循环往复直到所有任务都处理完毕。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值