<分区>
我正在学习 Java,但在同步方面遇到了麻烦。我想打印来自许多 Java 线程的数字列表,并让每个线程按顺序运行。我在使用同步时遇到问题,因为我不太了解。能帮忙看懂吗?
我希望输出能够看到这一点,但有时线程顺序错误。我想要:
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();
}
}
}
}
}