Hi Guys! Can you kindly run this code in your PC and see if are getting the correct output.... maybe there is something wrong with the path variable etc in my system...

thanks

I want to print numbers from 1 to 10 using two different Threads.

The code below is from a text book.....

I get the output correct sometimes, but when I re run the code, I get different output like 10 8 6 7 5 ... etc


public class CountDownApp
{
	public static void main(String[] args)
	{
		Thread count1 = new CountDownEven();
		Thread count2 = new CountDownOdd();
        count1.start();
		count2.start();
		
	}
}

class CountDownEven extends Thread
{
	public void run()
	{
		for(int i=10;i>0;i-=2)
		{   
			System.out.println(this.getName()+"count"+i);

			Thread.yield();
		}
	}
	
}

class CountDownOdd extends Thread 
{
	public void run()
	{
		for(int i=9;i>0;i-=2)
		{
			System.out.println(this.getName()+"count"+i);
	
			Thread.yield();
		}
	}
	
}
[/b]

any hints appreciated

If you are worrying why they are not printed orderly then they are not suppose to. They are threads and they are executed in parallel. So this output shouldn't be wrong:

10 8 6 9 4 7 2 5 3 1

The output is perfect

First of all, I think you mean you want to print out numbers from 10 to 1 and have a serial output.
Well like the other two posters have said, your output is fine and nothing is wrong with your machine because the way you wrote the code does not guarantee that you'll have a serial output all the time.
You can try using sleep method inplace of yield and check out the difference.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.