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

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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值