1.问题描述:
创建三个线程A,B,C,使A打印1-5,B打印6-10,C打印11-15,然后A又打印出16-20,B打印出21-25以此类推。。。。。
2.代码:
public class Main extends Thread{
Object o;
int id;
public static int i = 1;
public Main(Object o,int id) {
this.o = o;
this.id = id;
}
public static void main(String[] args) {
Object o = new Object();
Main a = new Main(o,0);
Main b = new Main(o,1);
Main c = new Main(o,2);
a.setName("A");
b.setName("B");
c.setName("C");
a.start();
b.start();
c.start();
}
@Override
public void run() {
synchronized (o) {
while(i<76) {
if(i/5%3 == this.id) {
for(int j = 0;j<5;j++) {
System.out.println(currentThread().getName() + ":"+ i++);
}
try {
o.notifyAll();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
try {
o.notifyAll();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
o.notify();
}
}
}
3.执行结果: