题目描述
问题描述:有4个线程和1个公共的字符数组。线程1的功能就是向数组输出A,线程2的功能就是向字符输出B,
线程3的功能就是向数组输出C,线程4的功能就是向数组输出D。要求按顺序向数组赋值ABCDABCDABCD,
ABCD的个数由线程函数1的参数指定。
输入描述:
输入一个int整数
输出描述:
输出多个ABCD
输入例子:
10
输出例子:
ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD
算法实现
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in );
while (scanner.hasNext()) {
int n = scanner.nextInt();
for (int i = 0 ; i < n; i++) {
System.out .print("ABCD" );
}
System.out .println();
}
scanner.close();
}
public static class WriteThread extends Thread {
private final int times;
private final String name;
private final AtomicInteger order;
private final int flag;
private final int all;
private final StringBuilder builder;
public WriteThread (int times, String name, AtomicInteger order, int flag, int all, StringBuilder builder) {
this .times = times;
this .name = name;
this .order = order;
this .flag = flag;
this .all = all;
this .builder = builder;
}
@Override
public void run () {
int count = 0 ;
while (count < times) {
if (order.get () == flag) {
count++;
builder.append(name);
order.set ((flag + 1 ) % all);
}
}
}
}
public static void main2 (String[] args) throws InterruptedException {
Scanner scanner = new Scanner(System.in );
List<Integer> input = new LinkedList<>();
while (scanner.hasNextLong()) {
input.add(scanner.nextInt());
}
List<StringBuilder> result = new LinkedList<>();
for (int num : input) {
StringBuilder builder = new StringBuilder();
result.add(builder);
AtomicInteger order = new AtomicInteger(0 );
WriteThread a = new WriteThread(num, "A" , order, 0 , 4 , builder);
WriteThread b = new WriteThread(num, "B" , order, 1 , 4 , builder);
WriteThread c = new WriteThread(num, "C" , order, 2 , 4 , builder);
WriteThread d = new WriteThread(num, "D" , order, 3 , 4 , builder);
a.start();
b.start();
c.start();
d.start();
a.join ();
b.join ();
c.join ();
d.join ();
}
for (StringBuilder b : result) {
System.out .println(b);
}
scanner.close();
}
}