I've written this code to obtain an alternate display of '|' and '*' starting with '|'. To ensure the altering of o/p I've used the yield(). But this doesn't seem to serve the purpose. Can someone point out where have I gone wrong ?

import java.util.*;

class Pat extends Thread
{
static int cnt=0;
}
class Pattern1 extends Pat

{

    public void run()
    {
    for(int i=1;i<=8;i++)
    {  try{
       System.out.print("|");
       cnt=1;
       if(cnt==1)
      this.yield();
       sleep(1000);
      }catch(Exception e){}     
    }   
    }
} 

class Pattern2 extends Pat

{   
    public void run()
    {
    for(int i=1;i<=7;i++)
    {  try{
       System.out.print("*");
       cnt=0;
       if(cnt==0)
       this.yield();
        sleep(1000);
       }catch(Exception e){}
    }

    }
} 

class Pattern

{
    public static void main(String args[])
    {
    Pattern1 p1=new Pattern1();
    Pattern2 p2=new Pattern2();

    p1.setPriority(2);
    p2.setPriority(1);

    p1.start();
    p2.start();

    }
}

Edited 3 Years Ago by Reverend Jim: Fixed formatting

I didn't read your code closely, but I do know that you either need to sleep, OR yield() not both....

yielding doesn't put the thread to sleep, it just relinquished the processor
for other threads to run, most likely before its time slice is up...

sleeping puts the thread to sleep and it wont continue to process until the time has expired AND it gets control of the processor again.....

if you explicitly want the |*|*| and have to use two threads to do it, then use semaphores or locks to synchronize the threads

if you explicitly want the |*|*| and have to use two threads to do it, then use semaphores or locks to synchronize the threads

hey friend, I'm not a pro...whats a lock ?

and I do intend to relinquish the processor hence using yield()...m using sleep() coz d processor is quiet fast n it process d entire thing in a single shot without giving d other thread a chance to execute

if you don't know what a semaphore or a lock is, well you have some reading to do on concurrent processing... locks are a way a synchronizing threads to cooperate with one another... semaphore is a version of a lock which has a counter... they are classes in
the java.util.concurrent library....

go to http://java.sun.com/javase/6/docs/api/

and start reading.... paticularly the
java.util.concurrent library, you will find a class called reentrant lock and semaphore

This article has been dead for over six months. Start a new discussion instead.