[英]Multi threading wait() notify()
Can someone please tell me whats wrong with the current program有人可以告诉我当前程序有什么问题吗
/*
* 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);
}
}
}
}
When EvenThread notifies why control is not going to OddThread.当 EvenThread 通知为什么控制不会去 OddThread 时。 I am using teo threads to print odd and even numbers, one thread to print odd numbers and one thread to print even numbers.
我使用 teo 线程打印奇数和偶数,一个线程打印奇数,一个线程打印偶数。 First i am trying to print 1 and 2 and later increment both values by 2.
首先,我试图打印 1 和 2,然后将这两个值都增加 2。
如果您的代码已经通过了添加 2 的点并且您没有任何循环返回到那里,您如何期望添加 2?
Your code does exactly what you've coded it to do.您的代码完全按照您编写的代码执行。
If you want to endlessly print numbers, you need to loop in both threads and restructure your code a little.如果你想无休止地打印数字,你需要在两个线程中循环并稍微重构你的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.