1 つの印刷 { 1,3,5,7,9} と別の印刷 {2,4,6,8,10} の 2 つのスレッドがあります。
{1,2,3,4,5,6,7...} を印刷したい
package com.oddnumber.threading;
public class NumberPrint implements Runnable {
int number=1;
private Object lock = new Object();
private volatile boolean isOdd = false;
public void generateEvenNumbers(int number) throws InterruptedException {
synchronized (lock) {
while (isOdd == false) {
lock.wait();
}
System.out.println("even" + number);
isOdd = false;
lock.notifyAll();
}
}
public void generateOddNumbers(int number) throws InterruptedException {
synchronized (lock) {
while (isOdd == true) {
lock.wait();
}
System.out.println("odd" + number);
isOdd = true;
lock.notifyAll();
}
}
@Override
public void run() {
while(true) {
if(number%2 == 0) {
try {
generateEvenNumbers(number);
number++;
Thread.sleep(1112);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
generateOddNumbers(number);
number++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
私はそれを使用して実行しました:
package com.oddnumber.threading;
public class Test
{
public static void main(String[] args) {
NumberPrint n1 = new NumberPrint();
NumberPrint n2 = new NumberPrint();
new Thread(n1).start();
new Thread(n2).start();
}
}
出力:
1
1
2
2
3
3
4
4
5
5
6
6
7
8
7
8
9
9
10
各数値は 2 回出力されますが、数値変数が 2 つのスレッド間で共有されないのはなぜですか?