• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

thread output

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 3323
86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 48
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
If you two don't stop this rough-housing somebody is going to end up crying. Sit down and read this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic