如何使用兩個線程交替打印1--100?

原文地址:https://blog.csdn.net/Java_stud/article/details/82347135java

做者:四兩數字先生[1]web

wait():令當前線程放棄 CPU 的資源,使別的線程能夠訪問共享的資源,而當前的線程排隊等待再次對資源的訪問微信

notify():喚醒正在排隊的等待的同步資源的線程,編輯器

notifyAll():喚醒正在排隊等待的全部的線程ide

測試java測試測試

在 java.lang.Object:flex

用這三個方法的注意點: 同步方法或者同步代碼塊裏this

使用兩個線程打印1----100.線程1和線程2交替打印spa

分析:.net

  1. 我先使用兩個線程打印1---100,(先不用交替打印)
  2. 而後在使用上面的三個方法,在代碼裏添加
public class PrintNum implements Runnable {

int num = 1;

@Override
public void run() {

synchronized (this) {
while (true) {
//喚醒wait()的一個或者全部線程
notify();
if (num <= 100) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + num);
num++;
} else {
break;
}

try {
wait();
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}

}

public class Test {

public static void main(String[] args) {
PrintNum printNum = new PrintNum();

Thread t1 = new Thread(printNum);
Thread t2 = new Thread(printNum);

t1.setName("甲");
t2.setName("乙");

t1.start();
t2.start();
}

}

運行效果:

參考資料

[1]

四兩數字先生: https://me.csdn.net/Java_stud


本文分享自微信公衆號 - 駭客與畫家(hacker-and-painter)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索