File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads 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 "Threads" Watch "Threads" New topic
Author

Threads

Sahil Manchanda
Ranch Hand

Joined: Jul 24, 2012
Posts: 41

can anybody tell why is the output guarnteed to be 4444 ? since rabbit is static, would it not be increased to 6 since there are 7 threads starting?


import java.util.*;
public class Toza extends Thread
{
static int rabbit=0; static boolean shifter=false; Toza toza;
public Toza(){}
public Toza(Toza q)
{
toza = q;
}
public static void main(String[] args) throws Exception
{
Toza tozax = new Toza();
List<Toza> stinger = new ArrayList<Toza>(); Toza toza = new Toza(tozax);
stinger.add(toza); toza = new Toza(tozax);
stinger.add(toza); toza = new Toza(tozax);
stinger.add(toza); toza = new Toza(tozax);
stinger.add(toza);
for (Object x : stinger)
{
((Toza)x).start();
}
for (Toza q : stinger)
{
q.hunter();
}
}
public synchronized void hunter() throws Exception {while (!shifter){waiter();} System.out.print(rabbit);}
public synchronized void run()
{
rabbit++;
if (rabbit > 3)
{
shifter=true;
}
}
public void waiter() throws Exception {Thread.sleep(100111);}
}
Don Redd
Ranch Hand

Joined: Jan 05, 2012
Posts: 82

Hi Sahil,

The output is guaranteed to be "4444"

At he end of first for loop in main method. the value of rabbit is 4 , since rabbit++ called only four times as there are only 4 threads running not 6 or 7


---Don Red
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Sahil Manchanda wrote:would it not be increased to 6 since there are 7 threads starting?


4 threads are updating variables and main thread is reading that variables. and each thread modification is visible to main thread , since they share common variable inside synchronized.

* comment while loop while (!shifter){waiter();} , and see ...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threads