【发布时间】:2018-04-08 18:37:19
【问题描述】:
现在我正在为标题中的任务而苦苦挣扎。我创建了 X 个线程,每个线程在循环中打印 Y 个相等的数字(从构造函数获取,例如“11111”、“222222”等)Z 次。所以结果看起来像:
111111111
222222222
333333333
111111111
222222222
333333333
对于 X = 3、Y = 9 和 Z = 2。 首先,我使用睡眠、中断并将“下一个”线程传递给前一个线程的构造函数解决了这个问题。一个中断另一个等。下一步是使用等待/通知而不是睡眠和中断来获得相同的输出。据我所见,有必要创建共享监视器对象,在每次打印后调用等待“我应该调用 notifyAll. 当前代码是:
public class PrinterController {
private static final int THREADS_NUMBER = 5;
public static void main(String[] args) {
Printer[] printers = new Printer[THREADS_NUMBER];
for (int i = 0; i < THREADS_NUMBER; i++) {
printers[i] = new Printer(i);
printers[i].start();
}
}
}
public class Printer extends Thread {
private static int portion = 10;
private static int totalNumber = 100;
private int digit;
private static final Object monitor = new Object();
public Printer(int digit) {
this.digit = digit;
}
@Override
public void run() {
synchronized (monitor) {
int portionsNumber = totalNumber / portion;
for (int i = 0; i < portionsNumber; i++) {
printLine();
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void printLine() {
for (int j = 0; j < portion; j++) {
System.out.print(digit);
}
System.out.println();
}
}
你能帮忙改进一下吗?我发现了类似的任务,但它们不包含适当的答案。谢谢。
基于 Nadir 答案的最终解决方案:
public class Printer extends Thread {
private static int portion = 10;
private static int totalNumber = 100;
private int digit;
static Object monitor = new Object();
static Integer counter = 0;
public Printer(int digit) {
this.digit = digit;
}
@Override
public void run() {
int portionsNumber = totalNumber / portion;
for (int i = 0; i < portionsNumber; i++) {
synchronized (monitor) {
while (digit != counter) {
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
printLine();
monitor.notifyAll();
}
}
}
private void printLine() {
for (int j = 0; j < portion; j++) {
System.out.print(digit);
}
System.out.println();
counter = (counter + 1) % PrinterController.THREADS_NUMBER;
}
}
【问题讨论】:
-
使用
CyclicBarrier或Phaser。 -
您是否需要使用
wait/notify,或者您是否允许使用Semaphore之类的实用程序? -
是的,只是等待/通知。
标签: java multithreading java-threads