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();
}
}
}
}
}
}
线程交替输出
最新推荐文章于 2023-07-16 19:25:32 发布