本篇內容介紹了“用JAVA多線程實現子線程循環10次,接著主線程循環100,接著又回到子線程循環10次,接著再回到主線程又循環100,如此循環50次”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
package com.study;
public class Demo001 {
public static void main(String[] args) {
Demo001 demo = new Demo001();
final OutPutClass putPutClass = demo.new OutPutClass();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int index = 1; index <= 50; index++) {
putPutClass.sub(index);
}
}
});
thread.start();
//由于main方法下面也是一個線程,并且是主線程
for (int index = 1; index <= 50; index++) {
putPutClass.main(index);
}
}
class OutPutClass {
private boolean isSync = true;
public synchronized void sub(int j) {
while(!isSync){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int index = 1;index <= 10;index ++){
System.out.println("當前線程【" + Thread.currentThread().getName() + "】正在執行sub,執行次數為:" + index + ",循環次數為:" + j);
}
isSync = false;
this.notify();
}
public synchronized void main(int j) {
while(isSync){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int index = 1;index <= 100;index ++){
System.out.println("當前線程【" + Thread.currentThread().getName() + "】正在執行main,執行次數為:" + index + ",循環次數為:" + j);
}
isSync = true;
this.notify();
}
}
}“用JAVA多線程實現子線程循環10次,接著主線程循環100,接著又回到子線程循環10次,接著再回到主線程又循環100,如此循環50次”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。