本文介绍了3 线程按顺序打印数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个简单的代码来按顺序打印数字.场景就像
I am trying to write a simple code to print numbers in sequence. Scenario is like
Thread Number
T1 1
T2 2
T3 3
T1 4
T2 5
T3 6
T1 7
T2 8
T3 9
...and so on.
这里是
public class ThreadNumberPrinter {
Object monitor = new Object();
AtomicInteger number = new AtomicInteger(1);
public static void main(String[] args) {
ThreadNumberPrinter tnp = new ThreadNumberPrinter();
Thread t1 = new Thread(tnp.new Printer(1, 3));
Thread t2 = new Thread(tnp.new Printer(2, 3));
Thread t3 = new Thread(tnp.new Printer(3, 3));
t3.start();
t1.start();
t2.start();
}
class Printer implements Runnable {
int threadId;
int numOfThreads;
public Printer(int id, int nubOfThreads) {
threadId = id;
this.numOfThreads = nubOfThreads;
}
public void run() {
print();
}
private void print() {
try {
while (true) {
Thread.sleep(1000l);
synchronized (monitor) {
if (number.get() % numOfThreads != threadId) {
monitor.wait();
} else {
System.out.println("ThreadId [" + threadId
+ "] printing -->"
+ number.getAndIncrement());
monitor.notifyAll();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
但是在第二个线程运行并打印数字 2 之后,所有线程都进入等待阶段并且没有打印任何内容.我不确定我哪里做错了.任何帮助将不胜感激.
But just after 2nd thread runs and prints the number 2, all thread get into wait stage and nothing gets printed. I am not sure where I am doing wrong.Any help would be greatly appreciated.
推荐答案
嗯,问题是模 3 % 3
是 0
.将您的 threadId
s 更改为 0..2
而不是 1..3
并希望它应该可以工作.
Well, the problem is that modulo 3 % 3
is 0
. Change your threadId
s to 0..2
instead of 1..3
and hopefully it should work.
这篇关于3 线程按顺序打印数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!