您好我试图在两个不同的线程的帮助下打印偶数和奇数但我无法获得输出.Below是程序。
public class oddeven
{
static volatile Integer t= 0;
public static void main(String as[])
{
Object ob = new Object ();
/*oddrunnable or= ;
evenrunnable er=;*/
Thread t1 = new Thread (new oddrunnable(t,ob),"odd");
Thread t2 = new Thread ( new evenrunnable(t,ob),"even");
t1.start();
t2.start();
}
}
class oddrunnable implements Runnable
{
Integer t ;
Object ob = new Object ();
public oddrunnable(Integer t,Object ob)
{
this.t = t;
this.ob= ob;
}
@Override
public void run()
{
// TODO Auto-generated method stub
synchronized (ob) {
while (true)
{if (t%2==0)
{
try {
ob.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Current thread id "+Thread.currentThread().getName()+"value of integer is "+t);;
t++;
ob.notify();
}
}
}
}
class evenrunnable implements Runnable
{
Integer t ;
Object ob = new Object ();
public evenrunnable(Integer t, Object ob)
{
this.t = t;
this.ob= ob;
}
@Override
public void run()
{
synchronized (ob) {
while (true)
{
if (t%2!=0)
{
try {
ob.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t++;
System.out.println("Current thread id "+Thread.currentThread().getName()+"value of integer is "+t);
ob.notify();
}
}
}
}
我想要输出如下:
Current thread id evenvalue of integer is 0
Current thread id oddvalue of integer is 1
Current thread id evenvalue of integer is 2
Current thread id oddvalue of integer is 3
Current thread id evenvalue of integer is 4
Current thread id oddvalue of integer is 5
Current thread id evenvalue of integer is 6
Current thread id oddvalue of integer is 7
但我错了,如下所示。
Current thread id evenvalue of integer is 1
Current thread id oddvalue of integer is 0
Current thread id oddvalue of integer is 1
Current thread id evenvalue of integer is 2
Current thread id evenvalue of integer is 3
Current thread id oddvalue of integer is 2
Current thread id oddvalue of integer is 3
Current thread id evenvalue of integer is 4
Current thread id evenvalue of integer is 5
Current thread id oddvalue of integer is 4
Current thread id oddvalue of integer is 5
Current thread id evenvalue of integer is 6
Current thread id evenvalue of integer is 7
Current thread id oddvalue of integer is 6
同时尝试调试程序时也会陷入困境。 我哪里错了?
答案 0 :(得分:4)
您的代码有一个问题是evenrunnable
和oddrunnable
都会增加一个不同的变量。每个人都有自己的t
成员。
如果您希望它们增加static volatile Integer t= 0;
,请从这些类中删除Integer t
实例变量。
将静态t
传递给这些类的构造函数只传递其引用的副本。由于Integer
是不可变的,t++
会创建一个新的Integer
并将其分配给实例变量t
,这不会影响静态变量t