アルゴリズム編-奇数偶数を交互に印刷
13209 ワード
タイトル
奇数を交互に印刷
リソースエンティティ
奇数スレッドの印刷
偶数スレッドの印刷
しゅかんすう
実行結果
奇数を交互に印刷
リソースエンティティ
public class Num {
int i = 1;
// true: false:
boolean flag = true;
}
奇数スレッドの印刷
public class PrintOddThread implements Runnable {
private final Num num;
public PrintOddThread(Num num) {
this.num = num;
}
@Override
public void run() {
while (num.i < 10000) {
synchronized (num) {
if (num.flag) {
System.out.println(" \t" + num.i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
num.i++;
num.flag = false;
} else {
try {
num.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
偶数スレッドの印刷
public class PrintEvenThread implements Runnable {
private final Num num;
public PrintEvenThread(Num num) {
this.num = num;
}
@Override
public void run() {
while (num.i < 10000) {
synchronized (num) {
if (!num.flag) {
System.out.println(" \t" + num.i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
num.i++;
num.flag = true;
} else {
num.notify();
}
}
}
}
}
しゅかんすう
public class App {
public static void main(String[] args) throws IOException {
ExecutorService executor = Executors.newFixedThreadPool(2);
Num num = new Num();
executor.execute(new PrintOddThread(num));
executor.execute(new PrintEvenThread(num));
executor.shutdown();
}
}
実行結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
......