问题描述
启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75. 程序的输出结果应该为:
线程1: 1
线程1: 2
线程1: 3
线程1: 4
线程1: 5
线程2: 6
线程2: 7
线程2: 8
线程2: 9
线程2: 10
...
线程3: 71
线程3: 72
线程3: 73
线程3: 74
线程3: 75
解法:采用java多线程回调的方法
回调类:
public class PrintCallback {
private int num;
private String threadName;
public PrintCallback() {
num = 0;
}
public synchronized void CallbackMethod(String threadName){
if (num <= 75) {
for (int i = 0; i < 5; i++) {
System.out.println(threadName+":"+(++num));
}
}
}
public void PrintNum() throws InterruptedException{
for (int i = 1; i < 6; i++) {
for (int j = 1; j < 4; j++) {
threadName = "线程"+j;
PrintThread runnable = new PrintThread(this);
Thread thread = new Thread(runnable);
thread.setName(threadName);
thread.start();
thread.join();
}
}
}
public static void main(String[] args) throws InterruptedException{
PrintCallback pc = new PrintCallback();
pc.PrintNum();
}
}
线程类:
public class PrintThread implements Runnable{
private PrintCallback pcback;
public PrintThread(PrintCallback pcback) {
this.pcback = pcback;
}
public void run() {
pcback.CallbackMethod(Thread.currentThread().getName());
}
}