File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How the Threads work?

 
fengzixuan zheng
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pleas analysis the results and explain how the two threads works:
public class ThreadTester {
public static void main(String args[]) {
HelloRunner hr=new HelloRunner();
Thread t1=new Thread(hr);
Thread t2=new Thread(hr);
t1.start();
t2.start();
}
}
class HelloRunner implements Runnable {
int i;
public void run() {
i=0;
while (true) {
System.out.println("Hello "+i++);
if (i==500) {
break;
}
}
}
}

[This message has been edited by fengzixuan zheng (edited October 14, 2001).]
 
Ragu Sivaraman
Ranch Hand
Posts: 464
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by fengzixuan zheng:
Pleas analysis the results and explain how the two threads works:
public class ThreadTester {
public static void main(String args[]) {
HelloRunner hr=new HelloRunner();
Thread t1=new Thread(r);
Thread t2=new Thread(r);
}
}
class HelloRunner implements Runnable {
int i;
public void run() {
i=0;
while (true) {
System.out.println("Hello "+i++);
if (i==500) {
break;
}
}
}
}

Thread t1=new Thread(r);
Thread t2=new Thread(r);
Its should be hr not r
These threads havent been started yet
So start the threads also
This code will produce unpredictable results since its OS dependent
So inside run, when the infinite loop hits 500, it will breakout and exit
 
Guoqiao Sun
Ranch Hand
Posts: 317
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Fengzixuan:
Your question is not very clear. You might want to ask question like the following code(I modified something):

If so, the programme will start two threads t1 and t2 and runs with result that is platform-dependent(print the number in a way that is not fixed).
If you define the run method as synchronised, the result will be predictable since the thread t1 will start first and lock the object HelloRunner when printing those numbers till it finished. Then thread t2 starts to print the number.
Hope it helps.
guoqiao

------------------
Guoqiao Sun
Sun Certified Programmer for Java™ 2 Platform
try my mock exam¹²³ at my homepage.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic