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 首次发布