看到一道题:
子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着在回到主线程100次,如此循环50次,请写出程序。
其实就是(子线程10 主线程100)X 50
这道题大概思路是 将主线程信息 与 子线程信息 封装到一个类 然后去调用循环
其实还是面向对象的思想 下面给出代码:
public class ThreadDemo {
public static void main(String[] args) {
final Deal deal = new Deal();
// 创建子线程
Thread subThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
deal.sub(i);
}
}
}) {
};
subThread.start();
// main则为主线程
for (int i = 1; i <= 50; i++) {
deal.main(i);
}
}
}
// 封装线程处理信息
class Deal {
// 布尔类型runSub 判断是否该子线程运行
private boolean runSub = true;
// 子线程信息 为了保持2个线程同步 2个方法加上锁
public synchronized void sub(int i) {
//如果不该子线程运行,等待唤醒
while (!runSub) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("Sub线程正在运行:" + j + "\t共计" + i);
}
runSub = false;
//唤醒主线程
this.notify();
}
// 主线程信息
public synchronized void main(int i) {
while (runSub) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int j = 1; j <= 50; j++) {
System.out.println("Main线程正在运行:" + j + "\t共计" + i);
}
runSub = true;
this.notify();
}
}