aspose file tools*
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
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "threads" Watch "threads" New topic
Author

threads

monojit choudhury
Greenhorn

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

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

public class Test_3{
public static void main(String args[]){
System.out.println("Starting");
Test p = new Test();
Thread t= new Thread(p);
t.start();
Thread.currentThread().setPriority(1);
p.inc();
p.dummy();
System.out.println("Main Over");
}
}
the output i get from this program is somethin like.....
Starting
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
Sure.
System.out.println("Starting");
// 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).
t.start();
Thread.currentThread().setPriority(1);
// 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.
p.inc();
// the new thread finishes off the loop, and dies nicely. Control goes back to your main thread, which calls dummy(), etc.
p.dummy();
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.
-Rob
 
wood burning stoves
 
subject: threads