I have just started learning threads. So i was trying to write few thread based programs.I wanted to print alphabets and numbers one after the other.
I used wait and notify for this. Now, I want to use yield for the same.
public class Y {
public static void main(String[] args) {
X an = new X(false);
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
try {
an.Alpha();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
try {
an.numbers();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
class X
{
boolean flag;
X(boolean flag)
{
this.flag = flag;
}
synchronized void Alpha() throws InterruptedException
{
for (char i = 'A'; i <= 'Z';i++)
{
while (flag == false)
{
System.out.println(+i);
//notifyAll();
flag = true;
}
Thread.yield();
//wait();
}
}
synchronized void numbers() throws InterruptedException
{
for (int i = 1;i <= 26;i++)
{
while (flag == true)
{
System.out.println(+i);
//notifyAll();
flag = false;
}
Thread.yield();
//wait();
}
}
}
I'm unable to get the same output as i'm getting with the wait/notify.
I know there's something missing that i don't understand about yield.Can anybody help in clearing my concept about yield and fix the above code.
Output with wait/notify : 65 1 66 2 67 3
Output with yield : 65 1