题目1
一个数组,多个线程去打印数组内容。要求多个线程按数组下标顺序打印,多个线程打印内容不能重复。
public class Main {
public static void main(String[] args) {
int id = 0;
Thread thread = new Thread(new Task(++id));
Thread thread1 = new Thread(new Task(++id));
Thread thread2 = new Thread(new Task(++id));
thread.start();
thread1.start();
thread2.start();
}
private static volatile int index = 0;
private static volatile int[] context = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private static int currentWorkerId = 1;
private static int totalWorker = 3;
private static int initWorkerId = 1;
private static Object lock = new Object();
static class Task implements Runnable {
private int id;
public Task(int id) {
this.id = id;
}
@Override
public void run() {
while (index < context.length) {
synchronized (lock) {
if (index < context.length) {
/**
* 这种方式是按照线程递增方式
* 线程递增到线程数量时,设置为初始
*/
if (currentWorkerId == id) {
System.out.println(Thread.currentThread().getName() + ":" + context[index++]);
if (currentWorkerId == totalWorker) {
currentWorkerId = initWorkerId;
} else {
currentWorkerId++;
}
lock.notifyAll();
}
}
}
}
}
}
}
题目2
A线程打印“A”,B线程打印“B”,C线程打印“C”,打印“ABC”10边。
public class PrintThread extends Thread {
private Object o;
private AtomicInteger actualIndex;
private Integer selfIndex;
private final String source;
public PrintThread(Object o, AtomicInteger actualIndex, Integer selfIndex, String source) {
this.o = o;
this.actualIndex = actualIndex;
this.selfIndex = selfIndex;
this.source = source;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (o) {
while (true) {
if (actualIndex.get() == selfIndex) {
System.out.print(source);
if (actualIndex.get() == 3) {
actualIndex.set(1);
System.out.println();
} else {
actualIndex.incrementAndGet();
}
o.notifyAll();
break;
} else {
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) {
Object o = new Object();
AtomicInteger actualIndex = new AtomicInteger(1);
PrintThread a = new PrintThread(o, actualIndex, 1, "A");
PrintThread b = new PrintThread(o, actualIndex, 2, "B");
PrintThread c = new PrintThread(o, actualIndex, 3, "C");
a.start();
b.start();
c.start();
}
}
网友评论