public class MultiThreadOrderPrint implements Runnable {
static Object o=new Object();
volatile static int index=0;
static int n=10; //线程数量
int max=100; //打印次数
int i; //线程名
public MultiThreadOrderPrint (int i) {
this.i=i;
}
public static void main(String[] args) {
for(int j=0;j<n;j++) {
(new Thread(new MultiThreadOrderPrint (j))).start();
}
}
public void run() {
while(true) {
synchronized (o) { //不加这个会卡死报异常
if(index>=max) {
o.notify();//加上这个可以结束
break;
}
if(index%n!=i) {
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
System.out.println(i+"-->"+index);
index++;
o.notifyAll();//只能用notifyAll,用notify会只执行一次卡死
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
java多线程交替打印
于 2023-10-16 19:41:58 首次发布
本文介绍了如何在Java中使用`MultiThreadOrderPrint`类和`Runnable`接口创建一个多线程程序,通过`synchronized`和`wait/notify`机制确保线程按顺序打印,避免了并发中的竞态条件。
5263

被折叠的 条评论
为什么被折叠?



