java 线程交替输出,[java]java经典问题之线程交替打印数字
問題
給出兩個線程,要求兩個線程交替打印從1到100,例如:A線程打印1,B線程打印2,A線程打印3...依次類推,直到打印到100
思路
這里主要是考察對java中wait/notifyAll機制的理解,可以開啟兩個線程,循環對數字進行自增,同時設置一個標記位,標記A線程是否對數字進行自增和打印,循環監聽該標記位的值,如果已經打印完成,則將A線程置為等待狀態,同時調用notifyAll,通知其它線程喚醒,線程B的操作與線程A相反
代碼實現
public class NumTest {
static Object object = new Object();
static int num = 0;
static volatile boolean aPrint = false;
static class A implements Runnable {
@Override
public void run() {
while (num < 99) {
synchronized (object) {
while (aPrint) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num++;
System.out.println(String.format("線程%s打印數字%d", Thread.currentThread().getName(), num));
aPrint = true;
object.notifyAll();
}
}
}
}
static class B implements Runnable {
@Override
public void run() {
while (num < 99) {
synchronized (object) {
while (!aPrint) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num++;
System.out.println(String.format("線程%s打印數字%d", Thread.currentThread().getName(), num));
aPrint = false;
object.notifyAll();
}
}
}
}
public static void main(String[] args) {
Thread threadA = new Thread(new A());
threadA.setName("threadA");
Thread threadB = new Thread(new B());
threadB.setName("threadB");
threadA.start();
threadB.start();
}
}
運行結果(部分):
image.png
這里解釋一下為什么while里面的判斷要用 num < 99,我們設想一下當num自增到98時,一定是有一個線程處理wait狀態,此時另一個線程做自增時,num變成了99,隨后執行notifyAll喚醒wait的線程,wait的線程蘇醒后繼續向下執行,再自增一次得到正確結果
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java 线程交替输出,[java]java经典问题之线程交替打印数字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows10如何添加uefi引导
- 下一篇: 关于weka中Instances的属性删