public class Test extends Thread {
static volatile int cnt = 0;
static int threadCount = 5;
int threadId;
public Test(int threadId) {
this.threadId = threadId;
}
@Override
public void run() {
while(!Thread.interrupted()){
synchronized (Object.class){
if(cnt % threadCount == threadId){
if(cnt>=100)break;
System.out.println(this.threadId +" "+ ++cnt);
}
}
if(cnt==100)Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
for (int i = 0; i < threadCount; i++) {
new Test(i).start();
}
}
}
n个线程按顺序输出1到100
最新推荐文章于 2024-07-13 22:56:10 发布