2つのスレッドが奇数偶数を交互に印刷-学習ノート
この間、アリの長兄が自分のアリの面接の経験を話しているのを見て、面接官に「2つのスレッドが奇数を交互に印刷する」プログラムを書くように要求された.先日、アリ兄貴がこのプログラムを専門に話しているブログ「マルチスレッド技術:2つのスレッドが奇数と偶数-明志健致遠-ブログ園を交互に印刷する」を見た.
主に安徽建築大学の文字を見て、その文章の中の兄貴の自己紹介を思い出して、きっとあの兄貴だと思います.
ブログを見て、今日は勉強ノートを書きます.「2つのスレッドが奇数偶数を交互に印刷する」ことを実現します.
本質的には,暗黙的ロックsynchronizedを用いてオブジェクトをロックし,次にオブジェクトのwaitとnotifyを再利用して実現する.
サボるために、全編で外部クラス1つ、静的内部クラス3つを書きました.
主に安徽建築大学の文字を見て、その文章の中の兄貴の自己紹介を思い出して、きっとあの兄貴だと思います.
ブログを見て、今日は勉強ノートを書きます.「2つのスレッドが奇数偶数を交互に印刷する」ことを実現します.
本質的には,暗黙的ロックsynchronizedを用いてオブジェクトをロックし,次にオブジェクトのwaitとnotifyを再利用して実現する.
サボるために、全編で外部クラス1つ、静的内部クラス3つを書きました.
package com.modest.cainiao;
/**
*
* @author heng.guo
* @date 2018-08-15
*/
public class PrintAlternately {
private static class Counter {
public int value = 1;
public boolean odd = true;
}
private static Counter counter = new Counter();
private static class PrintOdd implements Runnable {
@Override
public void run() {
while (counter.value <= 100) {
synchronized(counter) {
if (counter.odd) {
System.out.println(counter.value);
counter.value++;
counter.odd = !counter.odd;
// ,
counter.notify();
} else {
// ,
try {
counter.wait();
} catch (InterruptedException e) {}
}
}
}//while
}
}
private static class PrintEven implements Runnable {
@Override
public void run() {
while (counter.value <= 100) {
synchronized (counter) {
if (counter.odd) {
try {
counter.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(counter.value);
counter.value++;
counter.odd = !counter.odd;
counter.notify();
}
}//synchronized
}
}
}
public static void main(String[] args) {
new Thread(new PrintOdd()).start();
new Thread(new PrintEven()).start();
}
}