我正在学习Java,但是在synchronized方面遇到了麻烦。我想从许多Java线程中打印数字列表,并使每个线程按顺序进行。当我使用synchronized时,我遇到了问题,因为我不太理解。能否帮助我理解一下?
我希望输出结果像这样,但有时线程的顺序会错乱。我想要:
1-thread1
2-thread2
3-thread1
4-thread2
5-thread1
6-thread2
...
48-thread2
49-thread1
我的破碎的代码:
public class ManyThreadsAdd {
public static int index = 0;
public static void main(String[] args) {
ManyThreadsAdd myClass = new ManyThreadsAdd();
Thread thread1 = new Thread(myClass.new RunnableClass());
Thread thread2 = new Thread(myClass.new RunnableClass());
thread1.start();
thread2.start();
}
class RunnableClass implements Runnable {
public synchronized void run() {
while (index < 49) {
try {
Thread.sleep(100);
System.out.println(index+"-" +Thread.currentThread());
index = index + 1;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
wait()
和notify()
。为了实现你想要的输出,你需要线程之间进行某种形式的通信。 - TheLostMindt1,t2,...,tN,t1,t2,...,tN
?如果你要协调任意数量的线程,解决方案会更加复杂。 - Mike Strobel