有人可以告诉我当前节目的错误吗
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package evenodd;
import java.util.logging.Level;
import java.util.logging.Logger;
public class EvenOdd {
public static Integer i;
public static Integer y;
public static void main(String[] args) {
EvenOdd eo = new EvenOdd();
EvenThread et = new EvenThread(eo);
et.setName("EvenThread");
OddThread ot = new OddThread(eo);
ot.setName("OddThread");
et.start();
ot.start();
}
}
class EvenThread extends Thread{
EvenOdd eo;
public EvenThread(EvenOdd eo)
{
this.eo=eo;
}
public void run()
{
System.out.println("inside run "+Thread.currentThread().getName());
if(eo.y==null)
{
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(EvenThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
synchronized(eo)
{
if(eo.y==null)
{
eo.y=2;
System.out.println("Even Number " + eo.y);
}
else if(eo.y!=null)
{
System.out.println("Even Number " + eo.y+2);
}
System.out.println("notifying "+Thread.currentThread().getName());
eo.notify();
}
}
}
class OddThread extends Thread{
EvenOdd eo;
public OddThread(EvenOdd eo)
{
this.eo=eo;
}
public void run()
{
System.out.println("inside run "+Thread.currentThread().getName());
synchronized(eo)
{
if(eo.i==null)
{
eo.i=1;
System.out.println("Odd NUmber " + eo.i);
}
else if(eo.i!=null)
{
System.out.println("Odd NUmber " + eo.i+2);
}
try {
System.out.println("waiting "+Thread.currentThread().getName());
eo.wait();
} catch (InterruptedException ex) {
Logger.getLogger(OddThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
当EvenThread通知为什么控制不会进入OddThread时。我使用teo线程打印奇数和偶数,一个线程打印奇数,一个线程打印偶数。 首先,我尝试打印1和2,然后将两个值增加2。
答案 0 :(得分:1)
如果您的代码已经通过添加2并且您没有任何循环返回那里,您如何期望添加2?
答案 1 :(得分:0)
您的代码完全符合您的编码要求。
如果你想无休止地打印数字,你需要在两个线程中循环并稍微重构你的代码。