您的位置:首页 > 其它

N个线程轮流打印数字问题

2016-03-26 20:43 232 查看
//一个关于线程的经典面试题,要求用三个线程,按顺序打印1,2,3,4,5.... 71,72,73,74, 75.
//线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15.
//接着再由线程1打印16,17,18,19,20....以此类推, 直到线程3打印到75。

public class Printer implements Runnable {

int id;
static int num = 1;

public Printer(int id) {
this.id = id;
}

@Override
public void run() {
synchronized (Printer.class) {
while (num <= 75) {
if (num / 5 % 3 == id) {
System.out.print("id" + id + ":");
for (int i = 0; i < 5; i++)
System.out.print(num++ + ",");
System.out.println();
Printer.class.notifyAll();
} else {
try {
Printer.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

public static void main(String[] args) {

new Thread(new Printer(0)).start();
new Thread(new Printer(1)).start();
new Thread(new Printer(2)).start();
}
}

打印结果:

id0:1,2,3,4,5,
id1:6,7,8,9,10,
id2:11,12,13,14,15,
id0:16,17,18,19,20,
id1:21,22,23,24,25,
id2:26,27,28,29,30,
id0:31,32,33,34,35,
id1:36,37,38,39,40,
id2:41,42,43,44,45,
id0:46,47,48,49,50,
id1:51,52,53,54,55,
id2:56,57,58,59,60,
id0:61,62,63,64,65,
id1:66,67,68,69,70,
id2:71,72,73,74,75,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: