/**
* 子线程循环30次,主线程循环40次,再子线程循环30次,主线程循环40次,一共循环50轮
* @author zhangsong
*
*/
public class ThreadDemo {
private static SonThread thread = new SonThread();
public static void main(String[] args) {
new Thread(()->{
for(int i=1;i<=50;i++){
thread.sonMetod(i);
}
}).start();
for(int i=1;i<=50;i++){
thread.mainMetod(i);
}
}
}
class SonThread{
private boolean isSonThread = true;
public synchronized void sonMetod(int i){
if(!isSonThread){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=30;j++){
System.out.println("=======子线程第"+i+"轮,第"+j+"次!");
}
isSonThread = false;
notify();
}
public synchronized void mainMetod(int i){
if(isSonThread){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=40;j++){
System.out.println("主线程线程第"+i+"轮,第"+j+"次!");
}
isSonThread = true;
notify();
}
}
面试题:同步锁
最新推荐文章于 2022-06-24 08:52:45 发布