Я пытаюсь напечатать четные и нечетные числа, используя две разные темы.
Код указан ниже:
public class OddEvenThread extends Thread{
static Integer counter = 2;
static Object lock = new Object();
int max = 20;
public void printEven() throws InterruptedException{
synchronized(counter){
while(counter < (max-1)){
while(counter % 2 != 0){
System.out.println("Even thread Waiting");
counter.wait();
System.out.println("notified");
}
System.out.println("Even thread printing: "+ counter);
counter++;
System.out.println("Notifying odd thread"+counter);
counter.notify();
}
}
}
public void printOdd() throws InterruptedException{
synchronized(counter){
while(counter < (max-1)){
while(counter % 2 == 0){
System.out.println("Odd thread Waiting");
counter.wait();
System.out.println("notified");
}
System.out.println("Odd thread printing: "+ counter);
counter++;
System.out.println("Notifying even thread"+ counter);
counter.notify();
}
}
}
public static void main(String[] args) throws InterruptedException {
OddEvenThread t1 = new OddEvenThread(){
public void run(){
try {
printEven();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
OddEvenThread t2 = new OddEvenThread(){
public void run(){
try {
printOdd();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Complete");
}
}
Этот код не работает с разными выходами. Иногда печатается «Complete», иногда нет.
Пример выходных данных:
Odd thread printing: 1
Notifying even thread2
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at com.customthreadpool.OddEvenThread.printOdd(OddEvenThread.java:34)
at com.customthreadpool.OddEvenThread$2.run(OddEvenThread.java:53)
Если используется другой код блокировки stati c (ссылка 3), код работает нормально. В этом случае блок синхронизации выглядит так:
synchronized(lock){
while(counter < (max-1)){
while(counter % 2 != 0){
System.out.println("Even thread Waiting");
lock.wait();
System.out.println("notified");
}
System.out.println("Even thread printing: "+ counter);
counter++;
System.out.println("Notifying odd thread"+counter);
lock.notify();
}
}
Что мне не хватает в этом коде?