gpt4 book ai didi

Java 基本同步线程

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:12:07 27 4
gpt4 key购买 nike

<分区>

我正在学习 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();
}
}
}
}
}

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com