關於java執行緒的經典面試題。主執行緒子執行緒交替執行n次
阿新 • • 發佈:2019-02-04
子執行緒迴圈10次,接著主執行緒迴圈100次,接著又回到子執行緒迴圈10次,接著再回到主執行緒迴圈100次,如此迴圈50次
package com.lyf.practice;
/**
* Created by fangjiejie on 2017/4/24.
*/
public class ThreadTest2 {
private class Business{
boolean flag=true;//作為子執行緒和主執行緒誰來執行的標誌,true為子執行緒執行,主執行緒等待
public synchronized void SubThread(int i){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=0;j<10;j++){
System.out.println("子執行緒"+i+"執行"+j);
}
this .notifyAll();
flag=false;
}
public synchronized void MainThread(int i){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j=0;j<100;j++){
System.out.println("主執行緒"+i+"執行"+j);
}
this.notifyAll();
flag=true;
}
}
public void execute(){//主執行緒子執行緒輪迴執行50次
final Business business=new Business();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<50;i++){
business.SubThread(i);
}
}
}).start();
for(int i=0;i<50;i++){//兩個迴圈只能有一個來用執行緒啟動,否則。如果都用new Thread的方式,
// 一旦一個執行緒開啟,第二個執行緒必須等待其完成才能開啟,發生了死鎖現象。
business.MainThread(i);
}
}
public static void main(String[] args) {
new ThreadTest2().execute();
}
}