It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question in thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question in thread" Watch "Question in thread" New topic
Author

Question in thread

Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 208

public class Cert extends Thread
{
static int x=10;
public static void main( String args[] ) throws Exception
{
Cert Cert = new Cert();
Thread t1 = new Thread(Cert);
Thread t2 = new Thread(Cert);
t1.start();
t2.start();
}

public synchronized void run()
{
System.out.print(++x + " ");;
}
}


In the above program can the Output be guaranteed ???.........I think the output can be guaranteed as Both the Thread are running on different Objects......Am i Right ??


OCJP-90%,OCPWCD-95%
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 208

sagar shroff wrote:public class Cert extends Thread
{
static int x=10;
public static void main( String args[] ) throws Exception
{
Cert Cert = new Cert();
Thread t1 = new Thread(Cert);
Thread t2 = new Thread(Cert);
t1.start();
t2.start();
}

public synchronized void run()
{
System.out.print(++x + " ");;
}
}


In the above program can the Output be guaranteed ???.........I think the output can be guaranteed as Both the Thread are running on different Objects......Am i Right ??




Or Do the two Threads run on the same Object ...Please Help ??....
Rahul Sudip Bose
Ranch Hand

Joined: Jan 21, 2011
Posts: 637

sagar shroff wrote:





Well, you passed the same runnable Cert to both the threads and the run() method is synchronized.

See if this code helps :



OUTPUT :


SCJP 6. Learning more now.
Ikpefua Jacob-Obinyan
Ranch Hand

Joined: Aug 31, 2010
Posts: 394

@Sagar...Please always use code tags when writing programs...it makes it easier to analyse, you will find it at the top of the editor when creating your posts...
If you extend a Thread, override the run() method, pass 'a-Thread' or 'a-Runnable' to the threads constructor and invoke the start() method on the Thread Object, the 'new-thread-of-execution' is guaranteed to start and run to completion, provided there is NO other circumstance that alter the normal flow of the program.

Regards

Ikpefua


OCPJP 6.
In Your Pursuit Towards Certification, NEVER Give Up.
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 208

Thanks a lot Rahul......and Jacob yeah I will take care next time...nd thnks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question in thread
 
Similar Threads
join() method in Thread doesn't work as expected
Struggling to get wait()/notify() to work
Threads with separate lock Problem
join()