线程交替输出

import java.util.Scanner;
/**
 * 输入 int ,string 创建string.length()个线程,交替输出int遍字符 
 * 例如:2 abc
 * 创建三个线程,分别负责输出a,b,c,交替输出2次 故输出为abcabc
 * 
 * @author StSahana
 *
 */
public class Main {

    public static void main(String[] args) throws InterruptedException {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        String s[] = scan.next().split("");
        Main main = new Main();
        Object object[] = new Object[s.length];
        for (int m = 0; m < s.length; m++) {
            object[m] = new Object();
        }
        for (int j = 0; j < s.length; j++) {
            new Thread(main.new MyRunnable(s[j], i, object[(j + s.length - 1) % s.length], object[j])).start();
            Thread.sleep(1);
        }

    }

    public class MyRunnable implements Runnable {
        String out;// 要输出的字母
        int i;// 打印次数
        private Object pre;
        private Object self;

        public MyRunnable(String out, int i, Object pre, Object self) {
            this.out = out;
            this.i = i;
            this.pre = pre;
            this.self = self;
        }

        @Override
        public void run() {
            int x = i;
            while (x > 0) {
                synchronized (pre) {
                    synchronized (self) {
                        System.out.print(out);
                        x--;
                        self.notify();
                    }
                    try {
                        pre.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值