• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread output

 
Neeladyuti Chaudhury
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi ,

can anyone please give the output of the following with a proper explaination?


public class ThreadDemo
{
private int count = 1;
public synchronized void doSomething()
{
for (int i = 0; i < 10; i++)
System.out.println(count++);
}
public static void main(String[] args)
{
ThreadDemo demo = new ThreadDemo();
Thread a1 = new A(demo);
Thread a2 = new A(demo);
a1.start();
a2.start();
}
}
class A extends Thread
{
ThreadDemo demo;
public A(ThreadDemo td)
{
demo = td;
}
public void run()
{
demo.doSomething();
}
}


regards,
Neeladyuti
 
Tony Docherty
Bartender
Posts: 2953
59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the ranch.

Please use code tags when posting code.

can anyone please give the output of the following with a proper explaination?

Have you tried running it multiple times to see what happens?
 
Rakesh K. Cherukuri
Ranch Hand
Posts: 48
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Neeladyuti Chaudhury : More you are specific about your question better the chances you get a good response. Your post is very vague and people, who read it, cant even imagine what you are looking/asking for. Can you please rephrase the post to signify which part of it you want to understand ?
 
Sarfarajey Akram
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Neeladyuti

Welcome to Ranch

I agree with what Rakesh & Tony highlighted about your query. Below is what I understood, please repost if you asked something else.

Your code will output a sequence from 1-20. Sequence 1-10 will come from one thread and 11-20 will come from the other. It is not possible to say which thread prints which sequence as it depends on the thread scheduler.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic