Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple Thread Doubt -from Jane's Notes

 
swati bannore
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
In the Janes' Study Notes,there is a simple program which creates 2 threads and prints characters '!' and '*'.As per notes output shd be intermingled because the threads are running concurrently and are interleaved.
But when i run the same code, I do not get intermingled output.IS it perfectly the NOrmal behavior of Threads..?

Thanx
 
arie zwijnsma
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
when i run the code the output is intermingled.
i suspect on your machine thread t1 is finished before t2 has started. you can try to set the priority of t1 lower than the priority of t2, if this doesnt help make the for loop more timeconsuming by changing the for loop to for instance
for (int i=0;i<100;i++){
for(int j=0;j<10000;j++){for(int k=0;k<10000;k++){}}
System.out.print(c);
}
// bye
 
tvs sundaram
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
IMO, Such codes yield different o/p on different machines depending upon the speed of the system and OS.
Hope I am correct.
comments... welcome.
tvs sundaram
 
Mini Pilla
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,
I have another interesting output to share.
WHen i declaring i<10 it is ! followed by *
but when I am declaring i<100 or i<20 some
larger values it is all INTERMINGLED.So I
think it depends on the OS.
Thanx
Rajani

[This message has been edited by Rajani Katta (edited August 05, 2001).]
 
Dan Drillich
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try the following -
public class ThreadDemo extends Thread{
char c;
ThreadDemo(char c){
this.c = c;
}
public static void main(String args[]){
ThreadDemo t1 = new ThreadDemo('!');
ThreadDemo t2 = new ThreadDemo('*');
t1.start();
t2.start();
}
public void run(){

for (int i=0;i<100;i++)
{
System.out.print(c);
try {
sleep(2);
} catch (InterruptedException e) {}
}
}
}
 
swati bannore
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx all.
When I use sleep(2) as suggested by Dan, the output is intermingled.
I guess,it is OS specific.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic