jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes How the Threads work? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "How the Threads work?" Watch "How the Threads work?" New topic
Author

How the Threads work?

fengzixuan zheng
Ranch Hand

Joined: Aug 02, 2001
Posts: 31
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

Joined: Jul 20, 2001
Posts: 464
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

Joined: Jul 18, 2001
Posts: 317
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.


Guoqiao Sun<br />SCJP2 SCWCD2<br />Creator of <a href="http://www.jiris.com/" target="_blank" rel="nofollow">www.jiris.com</a>, Java resource, mock exam, forum
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How the Threads work?