Я довольно новичок в потоках и просто пытаюсь понять основы. Итак, я попробовал следующий код, чтобы печатать нечетные и четные числа один за другим.
Но я получаюнулевой указатель.
открытый класс P {
public static void main(String[] args) throws InterruptedException {
Print print = new Print(false);
Even e =new Even();
Odd o = new Odd();
e.start();
o.start();
}
}
класс Even extends Thread {Print print;
public void run()
{
try {
print.printeven();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Odd extends Thread {Print print;
public void run()
{
try {
print.printodd();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Print {
public boolean flag=false;
Print(boolean flag){
this.flag=flag;
}
synchronized void printodd() throws InterruptedException
{
for(int i=1;i<10;i=i+2)
if(!flag)
{
System.out.println(i);
notifyAll();
flag=true;
}
else
{
wait();
}
}
synchronized void printeven() throws InterruptedException
{
for(int i=2;i<=10;i=i+2)
if(flag)
{
System.out.println(i);
notifyAll();
flag=false;
}
else
{
wait();
}
}
}
Если кто-то могподробно объясните, что я делаю не так, и дайте основную идею, как отладить это.