有2个线程一个打印{1,3,5,7,9}。另一个打印{2,4,6,8,10}
我想打印 {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
每个数字打印两次,但是为什么两个线程之间不共享数字变量?