File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "threads" Watch "threads" New topic


monojit choudhury

Joined: Nov 20, 2000
Posts: 23
hi folks,
can anyone clear this out.

class Test implements Runnable{
int i =0;
synchronized void call_inc(){
void inc(){
while(i!= 15)
System.out.println(Thread.currentThread().getName() + " inc ---> " + i);
public void run(){
synchronized void dummy(){
System.out.println("dummy is being exceuted by " + Thread.currentThread().getName());

public class Test_3{
public static void main(String args[]){
Test p = new Test();
Thread t= new Thread(p);
System.out.println("Main Over");
the output i get from this program is somethin like.....
main inc ---> 1
main inc ---> 2
main inc ---> 3
main inc ---> 4
main inc ---> 5
main inc ---> 6
main inc ---> 7
main inc ---> 8
main inc ---> 9
Thread-0 inc ---> 10
Thread-0 inc ---> 11
Thread-0 inc ---> 12
Thread-0 inc ---> 13
Thread-0 inc ---> 14
Thread-0 inc ---> 15
dummy is being exceuted by main
Main Over
Press any key to continue . . .
now what i cant make out is .....why the main thread gives over to thread 0 aft i=9.
can anyone help me out.
thankx in advance.
Rob Whelan
Ranch Hand

Joined: Oct 18, 2000
Posts: 33
Oops.. posted twice. See below.
[This message has been edited by Rob Whelan (edited December 03, 2000).]
Rob Whelan
Ranch Hand

Joined: Oct 18, 2000
Posts: 33
// first, you create your Runnable, and a Thread to execute it.
Test p = new Test();
Thread t= new Thread(p);
// next, you call start(), a native method which starts to get the new thread running (though the method returns BEFORE that happens).
// you call the inc() method from your main thread. The new thread is still getting started, so the main thread gets through part of the loop before the new thread starts executing, and gets control. Remember, inc() is NOT synchronized, so thread control can flip back and forth unpredictably.;
// the new thread finishes off the loop, and dies nicely. Control goes back to your main thread, which calls dummy(), etc.
System.out.println("Main Over");

Make sense? Try having the main method call call_inc() instead of inc(), to see how forcing synchronization would change the output.
I agree. Here's the link:
subject: threads
It's not a secret anymore!