同学出去面试,遇到的一道面试题:先让子线程执行10次,再让主线程执行100次,之后子线程执行10次,主线程再执行100次,如此循环50次。
代码如下:
package com.thread;
public class ThreadCommunication2 {
public static void main(String[] args) {
final Bussiness b = new Bussiness();
//子线程
new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 50; i++) {
b.sub(i);
}
}
}).start();
//主线程
for (int i = 1; i <= 50; i++) {
b.main(i);
}
}
}
class Bussiness {
private boolean flag = true;
public synchronized void sub(int i) {
//如果不是自己 ,就等待
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("子线程循环" + j + "次,总循环" + i + "次");
}
flag = false;
this.notify();
}
public synchronized void main(int i) {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 100; j++) {
System.out.println("主线程循环" + j + "次,总循环" + i + "次");
}
flag = true;
this.notify();
}
}
把主线程和子线程写在一个类中,体现了程序的高内聚。