子線程循環10次,接着主線程循環100,接着又回到子線程循環10次,接着再回到主線程又循環100,如此循環50次,請寫出程序。
代碼如下:
/*
*子線程循環5次,接着主線程循環10次,接着又回到子線程循環5次,然後再到主線程循環10次,如此反覆執行5次;
*synchronized解決線程互斥
*/
public class ThreadSyn {
public static void main(String[] args) {
final Loop loop = new Loop();
// 子線程
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
loop.sun(i);
}
}
}).start();
// 主線程,mian方法本身就是一個主線程
for (int i = 1; i <= 5; i++) {
loop.mian(i);
}
}
}
class Loop {
private boolean iswait = true;
/*
* 這裏要注意wait和notify的用法,對象調用了wait方法就會使持有該對象的線程把該對象的控制權交出去,然後處於等待狀態。
* 任何一個時刻,對象的控制權(monitor)只能被一個線程擁有
*/
public synchronized void sun(int i) {
while (!iswait) {
try {
System.out.println("子線程等待。。。。。");
this.wait();// 等待主線程執行結束
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 5; j++) {
System.out.println("子線程:" + j + "循環次數" + i);
}
System.out.println("*******");
iswait = false;
this.notify();// 喚醒主線程
System.out.println(" 喚醒主線程");
}
public synchronized void mian(int i) {
while (iswait) {
try {
System.out.println("主線程等待。。。。。");
this.wait();// 等待子線程結束
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("主線程:" + j + "循環次數" + i);
}
System.out.println("^^^^^^^^^^");
iswait = true;
this.notify();// 喚醒子線程
System.out.println(" 喚醒子線程");
}
}
這裏有2個註釋不是很準,就是this.notify();這個方法我有點模糊,第一個notify按理來說應該是喚醒子線程,因爲this在sun()方法裏面,所以我這樣認爲的,不過this是代表當前對象,也就是Loop這個類,這裏我就更暈了,Loop又不是一個線程,this.notify是咋回事呢,反正我這樣寫出來了,notify不清楚也沒辦法了,只能以後再慢慢弄懂了