再发一道题。
题目:主线程100次,子线程50,交替执行50次。我看很多同学使用了join方法配合内部类。我仍然使用了信号器与发消息通知的结构实现。贴代码了。
public class Printer {
boolean flag = true;
public synchronized void printThreadA() {
if (flag) {
for (int i = 0; i < 100; i++) {
System.out.println("ThreadA's print count:" + i);
}
flag = false;
notify();
}
try {
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void printThreadB() {
if (flag) {
try {
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
System.out.println("ThreadB's print count isisisisisis:" + i);
}
flag = true;
notify();
}
}
public class ThreadChild implements Runnable {
Printer printer;
public ThreadChild(Printer printer) {
this.printer = printer;
}
public void run() {
for (int i = 0; i < 2; i++) {
printer.printThreadB();
}
}
}
public class ThreadMain implements Runnable {
Printer printer;
public ThreadMain(Printer printer) {
this.printer = printer;
}
public void run() {
for (int i = 0; i < 2; i++) {
printer.printThreadA();
}
}
}
public static void main(String[] args) {
Printer printer = new Printer();
ThreadMain tm = new ThreadMain(printer);
ThreadChild tc = new ThreadChild(printer);
Thread t = new Thread(tm);
t.start();
Thread tt = new Thread(tc);
tt.start();
}
已测试ok